using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Xml;
using System.Web;
using MBLocale;

public class RDLCTextBox
{
    protected String m_Name;
    protected String m_DefaultName;
    protected String m_Left;
    protected String m_Top;
    protected String m_ZIndex;
    protected String m_Width;
    protected String m_Height;
    protected bool m_CanGrow;
    protected String m_Source;
    protected String m_Value;
    protected Hashtable m_Style;
    protected bool m_CanShrink;

    public RDLCTextBox()
    {
        m_Name = "TextBox1";
        m_DefaultName = "TextBox1";
        m_Left = "0in";
        m_Top = "0in";
        m_ZIndex = "0";
        //m_Width = "0.5in";
        m_Height = "2in";
        m_CanGrow = true; ;
        m_CanShrink = true;
        m_Source = "External";
        m_Value = "";
    }
    public void writeElement(XmlTextWriter writer)
    {
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, this.m_Name);
        writer.WriteElementString("Left", this.m_Left);
        writer.WriteElementString("Top", this.m_Top);
        writer.WriteElementString("rd:DefaultName", this.m_DefaultName);
        writer.WriteElementString("ZIndex", this.m_ZIndex);
        if (m_Width != "")
            writer.WriteElementString("Width", this.m_Width);
        writer.WriteElementString("CanGrow", this.m_CanGrow.ToString().ToLower());
        writer.WriteElementString("CanShrink", this.m_CanShrink.ToString().ToLower());
        writer.WriteElementString("Height", this.m_Height);
        writer.WriteElementString("Value", this.m_Value);
        if (m_Style != null)
        {
            ICollection icol = m_Style.Keys;
            foreach (Object key in icol)
            {
                String strkey = (String)key;
            }
        }
        writer.WriteEndElement(); // Textbox
    }
    public void writeElement(XmlTextWriter writer, RDLCStyle rdlcStyle)
    {
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, this.m_Name);
        writer.WriteElementString("Left", this.m_Left);
        writer.WriteElementString("Top", this.m_Top);
        writer.WriteElementString("rd:DefaultName", this.m_DefaultName);
        writer.WriteElementString("ZIndex", this.m_ZIndex);
        writer.WriteElementString("Width", this.m_Width);
        writer.WriteElementString("CanGrow", this.m_CanGrow.ToString().ToLower());
        writer.WriteElementString("CanShrink", this.m_CanShrink.ToString().ToLower());
        writer.WriteElementString("Height", this.m_Height);
        writer.WriteElementString("Value", this.m_Value);
        if (m_Style != null)
        {
            rdlcStyle.writeRDLCStyle(writer, m_Style);
        }
        else if (rdlcStyle != null)
            rdlcStyle.writeRDLCStyle(writer);
        writer.WriteEndElement(); // Textbox
    }
    public String Name
    {
        get
        {
            return m_Name;
        }
        set
        {
            m_Name = value;
        }
    }
    public String DefaultName
    {
        get
        {
            return m_DefaultName;
        }
        set
        {
            m_DefaultName = value;
        }
    }
    public double Left
    {
        get
        {
            return Convert.ToDouble(m_Left.Replace("in", ""));
        }
        set
        {
            m_Left = Convert.ToString(value);
            m_Left = m_Left + "in";
        }
    }
    public double Top
    {
        get
        {
            return Convert.ToDouble(m_Top.Replace("in", ""));
        }
        set
        {
            m_Top = Convert.ToString(value);
            m_Top = m_Top + "in";
        }
    }
    public double Width
    {
        get
        {
            return Convert.ToDouble(m_Width.Replace("in", ""));
        }
        set
        {
            m_Width = Convert.ToString(value);
            m_Width = m_Width + "in";
        }
    }
    public double Height
    {
        get
        {
            return Convert.ToDouble(m_Height.Replace("in", ""));
        }
        set
        {
            m_Height = Convert.ToString(value);
            m_Height = m_Height + "in";
        }
    }
    public Boolean CanGrow
    {
        get
        {
            return m_CanGrow;
        }
        set
        {
            m_CanGrow = value;
        }
    }
    public Boolean CanShrink
    {
        get
        {
            return m_CanShrink;
        }
        set
        {
            m_CanShrink = value;
        }
    }
    public String Source
    {
        get
        {
            return m_Source;
        }
        set
        {
            m_Source = value;
        }
    }
    /// <summary>
    /// The attribute Value is really used in writing RDLC. if FieldName
    /// specified, the FieldName will be converted to Value
    /// </summary>
    public String Value
    {
        get
        {
            return m_Value;
        }
        set
        {
            m_Value = value;
        }
    }
    /// <summary>
    /// The FieldName attribute is not used directly. it automatically converted to Value
    /// </summary>
    public String FieldName
    {
        get
        {
            char[] arrch ={ '.', '!' };
            String[] str = m_Value.Split(arrch);
            return str[1];
        }
        set
        {
            m_Value = "=Fields!" + value + ".Value";
        }
    }
    public Hashtable Style
    {
        get
        {
            return m_Style;
        }
        set
        {
            m_Style = value;
        }
    }
}

public class RDLCImage
{
    protected string m_Name;
    protected string m_DefaultName;
    protected string m_Left;
    protected string m_Top;
    protected string m_ZIndex;
    protected string m_Width;
    protected string m_Height;
    protected string m_Sizing;
    protected string m_Source;
    protected string m_Value;
    protected string m_MIMEType;
    protected Hashtable m_Style;

    public RDLCImage()
    {
        m_Name = "image1";
        m_DefaultName = "image1";
        m_Left = "0in";
        m_Top = "0in";
        m_ZIndex = "0";
        m_Height = ".1in";
        m_Width = "2in";
        m_Source = "External";
        m_Value = "";
        m_Sizing = "AutoSize";
        m_MIMEType = "image/jpeg";
    }

    public void writeElement(XmlTextWriter writer)
    {
        writer.WriteStartElement("Image");
        writer.WriteAttributeString("Name", null, this.m_Name);
        writer.WriteElementString("Sizing", this.m_Sizing);
        writer.WriteElementString("Left", this.m_Left);
        writer.WriteElementString("Top", this.m_Top);
        //writer.WriteElementString("rd:DefaultName", this.m_DefaultName);
        writer.WriteElementString("ZIndex", this.m_ZIndex);
        if (m_Width != "")
            writer.WriteElementString("Width", this.m_Width);
        writer.WriteElementString("MIMEType", this.m_MIMEType);
        writer.WriteElementString("Height", this.m_Height);
        writer.WriteElementString("Source", this.m_Source);
        writer.WriteElementString("Value", this.m_Value);
        /*if (m_Style != null)
        {
            ICollection icol = m_Style.Keys;
            foreach (Object key in icol)
            {
                String strkey = (String)key;
            }
        }*/
        writer.WriteEndElement();
    }

    public string Value
    {
        get { return m_Value; }
        set { m_Value = value; }
    }

    public double Left
    {
        get
        {
            return Convert.ToDouble(m_Left.Replace("in", ""));
        }
        set
        {
            m_Left = Convert.ToString(value);
            m_Left = m_Left + "in";
        }
    }
    public double Top
    {
        get
        {
            return Convert.ToDouble(m_Top.Replace("in", ""));
        }
        set
        {
            m_Top = Convert.ToString(value);
            m_Top = m_Top + "in";
        }
    }
    public double Width
    {
        get
        {
            return Convert.ToDouble(m_Width.Replace("in", ""));
        }
        set
        {
            m_Width = Convert.ToString(value);
            m_Width = m_Width + "in";
        }
    }
    public double Height
    {
        get
        {
            return Convert.ToDouble(m_Height.Replace("in", ""));
        }
        set
        {
            m_Height = Convert.ToString(value);
            m_Height = m_Height + "in";
        }
    }
}

public class MyKeyValuePair
{
    private String m_key = null;
    private Object m_value = null;
    private String m_elementtype = "value";

    public String elementType
    {
        get
        {
            return m_elementtype;
        }
        set
        {
            m_elementtype = value;
        }
    }


    public String key
    {
        get
        {
            return m_key;
        }
        set
        {
            m_key = value;
        }
    }

    public Object value
    {
        get
        {
            return m_value;
        }
        set
        {
            m_value = value;
        }
    }

    public MyKeyValuePair()
    {
    }
}

/**
 * Writes RDLC Style in RDLC.
 * The contaner for all the style folder is "Style". Inside "Style" folder
 * there are many sub folders. the sub folder contains style information.
 * The "heading" variable points the sub folder where to look for style.
 * It checks whether any folder exist with the name. if not found the "Default" folder is used
 * 
 */

public class RDLCStyle
{
    ArrayList m_style = null;
    String mydir = null;
    public String heading = null;
    public String absfilepath = null;

    public void addStyle(String key, String value)
    {
        MyKeyValuePair mkvp = new MyKeyValuePair();
        mkvp.key = key;
        mkvp.value = value;
        m_style.Add(mkvp);
    }

    public String getStyle(String key)
    {
        for (int i = 0; i < m_style.Count; i++)
        {
            MyKeyValuePair tmp = (MyKeyValuePair)m_style[i];
            if (tmp.key.Equals(key))
            {
                return (String)tmp.value;
            }
        }
        return null;
    }

    public void writeRDLCStyle(XmlTextWriter writer)
    {
        writer.WriteStartElement("Style");
        for (int i = 0; i < m_style.Count; i++)
        {
            MyKeyValuePair tmp = (MyKeyValuePair)m_style[i];
            if (tmp.elementType.Equals("element"))
            {

            }
            else
            {
                if (tmp.key.Equals("BorderStyle"))
                {
                    writer.WriteStartElement("BorderStyle");
                    writer.WriteElementString("Default", (String)tmp.value);
                    writer.WriteEndElement();//BorderStyle
                }
                else
                    writer.WriteElementString(tmp.key, (String)tmp.value);
            }
        }
        writer.WriteEndElement(); // Style
    }

    public void writeRDLCStyle(XmlTextWriter writer, Hashtable hsStyle)
    {
        writer.WriteStartElement("Style");
        foreach (string sKey in hsStyle.Keys)
        {
            writer.WriteElementString(sKey, hsStyle[sKey].ToString());
        }
        writer.WriteEndElement(); // Style
    }

    public void init()
    {
        if (heading == null)
        {
            heading = "Default";
        }
        processRDLCStyle();
    }

    public void init(String heading)
    {
        this.heading = heading;
        processRDLCStyle();
    }

    public void processRDLCStyle()
    {
        m_style = new ArrayList();
        FileStream stream1 = File.OpenRead(absfilepath);
        StreamReader sr = new StreamReader(stream1);
        ArrayList lines = new ArrayList();
        String line;
        String tmpHeading = "[" + heading + "]";
        int found = 0;
        while ((line = sr.ReadLine()) != null)
        {
            line = line.Trim();
            if (line.Equals(tmpHeading))
            {
                found = 1;
            }
            if (found == 1)
            {
                if (line.StartsWith("[") && line.EndsWith("]") && !line.Equals(tmpHeading))
                {
                    found = 2; break;
                }
                if (!line.Equals(""))
                    lines.Add(line);
            }
        }
        MyKeyValuePair mkvp = null;
        for (int i = 0; i < lines.Count; i++)
        {
            String tmp = (String)lines[i];
            string[] arr = tmp.Split(':');
            if (arr.Length == 3)
            {
                mkvp = new MyKeyValuePair();
                mkvp.key = arr[0].Trim();
                mkvp.value = arr[1].Trim();
                m_style.Add(mkvp);
            }
            else if (arr.Length == 2)
            {
                mkvp = new MyKeyValuePair();
                mkvp.key = arr[0].Trim();
                mkvp.value = arr[1].Trim();
                m_style.Add(mkvp);
            }
        }
        stream1.Flush();
        stream1.Close();
        stream1.Dispose();
        stream1 = null;
        sr.Close();
        sr.Dispose();
        sr = null;
    }

    public RDLCStyle()
    {
        m_style = new ArrayList();
    }

    public ArrayList Style
    {
        get
        {
            return m_style;
        }
    }
}

/**
 * This Class has the ability to build RDLC file dynamically
 */

public class MyRDLC
{
    public SqlConnection m_connection;

    protected String m_commandText = null;
    protected ArrayList m_fields;
    protected ArrayList m_FieldLength = null;
    protected ArrayList m_DateTime = null;
    public double dReportWidth = 0;
    public XmlTextWriter writer = null;
    public FileStream stream;
    public String m_datasourceid = "5ea82cd9-bc77-45d7-b0ab-6da09978eeb2";
    public String m_reportid = "6f446dcd-7527-4b4f-8b22-2f46b1e86179";
    protected RDLCStyle styl = null;
    public String serverPath = null;
    public String styleName = "Default";

    protected String m_connectionString = null;

    protected ArrayList arrCol = null;
    protected ArrayList arrRow = null;
    protected String aggField = null;
    protected String rowGroupingField = "attrib_id";
    protected String columnGroupingField = "object_id";

    private bool m_EnableHyperLink = false; // Added by 'Imran Gani' on 13/02/2012, for HyperLink Properties setting.
    public string ExportType = ""; // Added by 'Imran Gani' on 15-Oct-2013, (copied from Nithya for Handleing css properties in export option)
    /// <summary>
    /// To set HyperLink Properties as Enable/Disable.
    /// Boolean value true/false.
    /// </summary>
    public bool EnableHyperLink
    {
        get
        {
            return m_EnableHyperLink;
        }
        set
        {
            m_EnableHyperLink = value;
        }
    }

    public String connectionString
    {
        get
        {
            return m_connectionString;
        }
        set
        {
            m_connectionString = value;
        }
    }

    /*public static void Main()
    {
        RdlGenerator myRdlGenerator = new RdlGenerator();
        myRdlGenerator.Run();
    }*/

    public void init()
    {
        styl = new RDLCStyle();
        styl.heading = "RowGrouping";
        styl.absfilepath = serverPath + "\\Style\\" + styleName + "\\mystyle.txt";
        styl.init();
    }

    public String commandText
    {
        get
        {
            return m_commandText;
        }
        set
        {
            m_commandText = value;
        }
    }

    public void GenerateReportFromDataset(DataSet dsReportInput, ref MemoryStream msReport, ref float ReportWidth, string exportType) // modified by 'Imran Gani' on 15-Oct-2013, (copied from Nithya for report export performance issue)
    {
        //string constr = HttpContext.Current.Session["dbcon"].ToString();
        //string sSql = getSql(dsReportInput);
        string sReportName = "";

        if (dsReportInput.Tables["p_report_header_footer"] != null) //Modified By Dhanapal On Dec 10 2010
        {
            if (dsReportInput.Tables["p_report_header_footer"].Rows.Count > 0)
                sReportName = dsReportInput.Tables["p_report_header_footer"].Rows[0]["rpt_title"].ToString().Trim();
        }

        if (sReportName == "") sReportName = getReportProperties("rpt_name", dsReportInput);
        if (sReportName == "") sReportName = getReportProperties("rpt_id", dsReportInput);
        string sReportType = getReportProperties("rpt_type", dsReportInput);
        ExportType = exportType;// Added by 'Imran Gani' on 15-Oct-2013, (copied from Nithya for Handleing css properties in export option)
        //this.connectionString = constr;
        //this.OpenConnection();

        bool bHasRows = GenerateFieldsList(dsReportInput, "", ref ReportWidth);//bool bHasRows = GenerateFieldsList(dsReportInput, sSql, ref ReportWidth);
        //mrdlc.init();

        string sTempReportName = sReportName + "_" + HttpContext.Current.Session["userid"].ToString() + "_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
        serverPath = HttpContext.Current.Server.MapPath(".");
        if (!Directory.Exists(serverPath + "\\report"))
            System.IO.Directory.CreateDirectory(serverPath + "\\report");
        string absReportPath = serverPath + "\\report\\" + HttpUtility.UrlEncode(sTempReportName) + ".rdlc";
        //commandText = sSql;
        init();
        writeInitRDLC(absReportPath);
        writeDataSource("DataSource1");
        writeReportParameter();
        writeDataset(dsReportInput); //Modified by 'Imran Gani' on 10/02/2012, for HyperLink properties Setting.

        if (sReportType == "") sReportType = "tabular";
        switch (sReportType.ToLower())
        {
            default:
            case "tabular":
                GenerateRdl(absReportPath, sReportName, getReportProperties("rpt_desc", dsReportInput), dsReportInput);
                break;
            //    /*case "matrix":
            //        mrdlc.GenerateMatrixRdl(absReportPath);
            //        break;*/
        }

        //MemoryStream msReport = null;
        writeEndRDLC(ref msReport, absReportPath);
        //return msReport;
    }

    public void GenerateReportFromReportId(string ReportId)
    {

    }

    #region Functions to get ReportProperties

    private string getSql(DataSet dsReportInput)
    {
        string sSql = "";
        if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true")
        {
            string sSqlId = dsReportInput.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString();
            sSql = getPredefinedSQL(sSqlId);
        }
        else
        {
            //DataSet dsReportInput = (DataSet) Session["ReportInput"];
            string sTableName = getObjectName(dsReportInput.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString());
            if (sTableName != "")
            {
                string sFieldName = getFieldNames(dsReportInput.Tables["p_sy_report_att"], sTableName);

                if (sFieldName != "")
                {
                    sSql = "Select " + sFieldName + " from " + sTableName;
                }
            }
        }

        return sSql;
    }

    private string getObjectName(string ObjectId)
    {
        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["dbcon"].ToString());
        string sObjectName = hdd.GetColumnValue("Select object_table from sy_obj where object_id = '" + ObjectId + "'");
        return sObjectName;
    }

    private string getPredefinedSQL(string SQL_id)
    {
        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["dbcon"].ToString());
        string sSQL = hdd.GetColumnValue("Select report_base_sql from sy_report_sql where report_base_id=" + SQL_id);
        if (sSQL.Contains("$") || sSQL.Contains("#"))
            sSQL = ReplaceParameters(sSQL);
        return sSQL;
    }

    private string ReplaceParameters(string SQL)
    {
        string sTemp = "ctl00$ContentPlaceHolder3$wz_Report$txt_";
        sTemp = "txt_";
        if (HttpContext.Current.Request.UrlReferrer.AbsolutePath.ToLower().EndsWith("report.aspx"))
            sTemp = "txt_";
        else if (HttpContext.Current.Request.UrlReferrer.AbsolutePath.ToLower().EndsWith("reportwizard.aspx"))
            sTemp = "ctl00$ContentPlaceHolder3$wz_Report$txt_";
        Hashtable hsParam = new Hashtable();
        hsParam = getParameters(SQL, "$", ref hsParam);
        hsParam = getParameters(SQL, "#", ref hsParam);
        foreach (string sParam in hsParam.Keys)
        {
            if (sParam.StartsWith("#") && sParam.EndsWith("#"))
                SQL = SQL.Replace(sParam, GetLocalizedDateTime(sTemp, sParam));
            else
                SQL = SQL.Replace(sParam, HttpContext.Current.Request.Form[sTemp + sParam]);
        }
        return SQL;
    }

    private string GetLocalizedDateTime(string sTemp, string sParam)
    {
        string sRet = "";
        try
        {
            sRet = HttpContext.Current.Request.Form[sTemp + sParam];
            #region Old Code commmented by 'Imran Gani' on 28-Feb-2014, for locale support
            //Localization li = new Localization();
            //DateTime dt = DateTime.Parse(sRet, li.getUserCulture());
            //sRet = dt.ToString();
            //li = null;
            #endregion
            DateTime dt = DateTime.Parse(sRet, MBLocalization.getCultureInfo(HttpContext.Current.Session["userlocale"].ToString()));
            sRet = dt.ToString();
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("ReplaceDateTime : Error : " + Ex.Message);
            //sRet = Request.Form["ctl00$ContentPlaceHolder3$wz_Report$txt_" + sParam];
        }
        return sRet;
    }

    private Hashtable getParameters(string sSql, string sChar, ref Hashtable hsParam)
    {
        try
        {
            int iPos = 0;

            while (iPos < sSql.Length & iPos != -1)
            {
                string sParam = "";
                iPos = sSql.IndexOf(sChar, iPos);
                if (iPos != -1)
                {
                    int iEndPos = sSql.IndexOf(sChar, iPos + 1);
                    if (iEndPos == -1)
                        iEndPos = sSql.Length - iPos;
                    else
                        iEndPos = iEndPos - (iPos - 1);
                    sParam = sSql.Substring(iPos, iEndPos);
                    sParam = sParam.TrimEnd('\'');
                    if (!hsParam.Contains(sParam))
                        hsParam.Add(sParam, "");
                    iPos = iPos + iEndPos;
                }
            }

            //hsParam = getParameters(sSql, "#",ref hsParam);
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("getParameters : Error : " + Ex.Message);
        }

        return hsParam;
    }
    private string getUTCHours(string sUTC_Offset)
    {
        string sHours = "+0";
        try
        {
            if (sUTC_Offset != "")
            {
                if (sUTC_Offset.IndexOf(".") != -1)
                    sHours = sUTC_Offset.Substring(0, sUTC_Offset.IndexOf('.'));
                else
                    sHours = sUTC_Offset.Trim();

                if (sUTC_Offset.StartsWith("-"))
                    sHours = "-" + sHours;
                else
                    sHours = "+" + sHours;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getUTCHours : Error : " + ex.Message);
            return "+0";
        }
        return sHours;
    }

    private string getUTCMinutes(string sUTC_Offset)
    {
        string sMinutes = "+0";
        try
        {
            if (sUTC_Offset != "")
            {
                sMinutes = sUTC_Offset.Substring(sUTC_Offset.IndexOf('.') + 1, sUTC_Offset.Length - sUTC_Offset.IndexOf('.') - 1);

                if (sUTC_Offset.StartsWith("-"))
                    sMinutes = "-" + sMinutes;
                else
                    sMinutes = "+" + sMinutes;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUTCMinutes : Error : " + ex.Message);
            return "+0";
        }
        return sMinutes;
    }

    private string getDTSQL(string FieldName, string sHours, string sMinutes)
    {
        string sDateAdd = "";
        try
        {
            if (sMinutes != "")
                sDateAdd = "dateadd(mi, " + sMinutes + ",[" + FieldName + "])";
            if (sHours != "")
            {
                if (sDateAdd == "")
                    sDateAdd = "dateadd(hh, " + sHours + ",[" + FieldName + "])";
                else
                    sDateAdd = "dateadd(hh, " + sHours + "," + sDateAdd + ")";
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDTSQL : Error : " + ex.Message);
            return FieldName;
        }
        return sDateAdd;
    }

    private string getUserIdSQL(string FieldName, string ObjectName)
    {
        string sUserSQL = "";
        try
        {
            sUserSQL = "(SELECT user_id AS " + FieldName + " from sy_usr as usr where (usr.af_row_id=" + ObjectName + "." + FieldName + ")) as " + FieldName + " ,";
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getUserIdSQL : Error : " + ex.Message);
            sUserSQL = FieldName;
        }

        return sUserSQL;
    }

    private string getFieldNames(DataTable dtAttribute, string sObjectName)
    {
        string sFields = "";
        DynamicDisplayI DDI = new DynamicDisplayI();
        string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");

        string sHrs = getUTCHours(sUTC_Offset);
        string sMins = getUTCMinutes(sUTC_Offset);

        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["dbcon"].ToString());
        foreach (DataRow dr in dtAttribute.Rows)//Select("", "attrib_sequence asc")
        {
            string sAttrib_id = dr["attrib_id"].ToString();
            // Added by srivatsan on June 15 2009 for owner id field
            if (sAttrib_id.ToLower() == "created_by" || sAttrib_id.ToLower() == "modified_by" || sAttrib_id.ToLower() == "owner_id")
            {
                sFields += getUserIdSQL(sAttrib_id, sObjectName);
            }
            else
            {
                string sDatatype = hdd.GetColumnValue("select attrib_data_type from sy_obj_att where object_id='" + dr["object_id"].ToString() + "' and attrib_id = '" + sAttrib_id + "'");
                if (sDatatype == "DT")
                {
                    string sDateAdd = getDTSQL(sAttrib_id, sHrs, sMins);
                    sFields = sFields + sDateAdd + " as " + sAttrib_id + ", ";
                }
                else
                    sFields = sFields + "[" + sAttrib_id + "], "; //+ "] as [" + dr["caption"].ToString() + "], " ;
            }
        }
        sFields = sFields.Trim();
        if (sFields.EndsWith(","))
            sFields = sFields.Remove(sFields.Length - 1, 1);
        return sFields;
    }

    private string getReportProperties(string FieldName, DataSet dsReportInput)
    {
        string sReportName = "";
        if (dsReportInput.Tables["p_sy_report"] != null)
        {
            sReportName = dsReportInput.Tables["p_sy_report"].Rows[0][FieldName].ToString();
        }
        return sReportName;
    }

    #endregion

    /*public void buillRDLC(String absFilePath)
    {
        try
        {
            // Call methods to create the RDL
            this.OpenConnection();
            this.GenerateFieldsList();
            this.GenerateRdl(absFilePath);

            //Console.WriteLine("RDL file generated successfully.");
        }

        catch (Exception exception)
        {
            //Console.WriteLine("An error occurred: " + exception.Message);
        }

        finally
        {
            // Close the connection string
            m_connection.Close();
        }
    }*/

    public void OpenConnection()
    {
        // Create a connection object
        m_connection = new SqlConnection();

        // Create the connection string
        //m_connectString = @"data source=localhost;initial catalog=AdventureWorks;integrated security=SSPI";
        //m_connectString = @"Data Source=.;Initial Catalog=Report;User Id=sa;Password=";
        //m_connectString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=\"D:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\MSSQL\\Data\\mytest.mdf\";Integrated Security=True;Connect Timeout=30;User Instance=True";
        m_connection.ConnectionString = m_connectionString;

        // Open the connection
        m_connection.Open();
    }

    public bool GenerateFieldsList(DataSet dsInput, String sql, ref float ReportWidth)
    {
        bool bHasRows = true;
        try
        {
            #region MyRegion
            // SqlCommand command;
            // SqlDataReader reader;
            // int iStringFields = 0;
            // if (m_commandText == null) m_commandText = sql;
            // // Executing a query to retrieve a fields list for the report
            // command = m_connection.CreateCommand();
            // #region MyRegion
            // /*m_commandText =
            //"SELECT Person.CountryRegion.Name AS CountryName, Person.StateProvince.Name AS StateProvince " +
            //"FROM Person.StateProvince " +
            //"INNER JOIN Person.CountryRegion ON Person.StateProvince.CountryRegionCode = Person.CountryRegion.CountryRegionCode " +
            //"ORDER BY Person.CountryRegion.Name";*/

            // #endregion
            // command.CommandText = m_commandText;

            // // Execute and create a reader for the current command
            // reader = command.ExecuteReader(CommandBehavior.SchemaOnly);
            // DataTable dtSchema = reader.GetSchemaTable();
            // bHasRows = reader.HasRows;
            // reader.Close();
            // #region MyRegion
            // // For each field in the resultset, add the name to an array list
            // /*m_fields = new ArrayList();
            // for (int i = 0; i < dtSchema.Rows.Count; i++)
            // {
            //     m_fields.Add(reader.GetName(i));
            // }*/

            // #endregion

            // DataTable dtTable = null;
            // //if (HttpContext.Current.Session["ReportInput"] != null)
            // //{
            // //    DataSet dsInput = (DataSet)HttpContext.Current.Session["ReportInput"];
            // dtTable = dsInput.Tables["p_sy_report_att"];
            // //}
            // // For each field in the resultset, add the name to an array list
            // m_fields = new ArrayList();
            // m_FieldLength = new ArrayList();
            // m_DateTime = new ArrayList();
            // foreach (DataRow dr in dtTable.Rows/*dtSchema.Rows*/)
            // {
            //     //string sColumnName = dr["ColumnName"].ToString();
            //     string sColumnName = dr["attrib_id"].ToString();
            //     DataRow[] drSelect = dtSchema.Select("ColumnName='" + sColumnName + "'");
            //     if (drSelect.Length > 0)
            //     {
            //         m_fields.Add(sColumnName);

            //         switch (drSelect[0]["DataType"].ToString())
            //         {
            //             case "System.Int32":
            //             case "System.Byte":
            //             case "System.Decimal":
            //                 if (sColumnName.Length > 5)
            //                 {
            //                     double dTemp = sColumnName.Length * 0.1 + 0.5;
            //                     m_FieldLength.Add(dTemp.ToString() + "in");
            //                     dReportWidth = dReportWidth + dTemp;
            //                 }
            //                 else
            //                 {
            //                     m_FieldLength.Add(".5in");
            //                     dReportWidth = dReportWidth + 0.5;
            //                 }
            //                 break;
            //             case "System.DateTime":
            //                 m_DateTime.Add(sColumnName);
            //                 if (sColumnName.Length > 15)
            //                 {
            //                     double dTemp = sColumnName.Length * 0.1;
            //                     m_FieldLength.Add(dTemp.ToString() + "in");
            //                     dReportWidth = dReportWidth + dTemp;
            //                 }
            //                 else
            //                 {
            //                     m_FieldLength.Add("1.7in");
            //                     dReportWidth = dReportWidth + 2.1;
            //                 }
            //                 break;
            //             case "System.Boolean":
            //                 if (sColumnName.Length > 5)
            //                 {
            //                     double dTemp = sColumnName.Length * 0.1;
            //                     m_FieldLength.Add(dTemp.ToString() + "in");
            //                     dReportWidth = dReportWidth + dTemp;
            //                 }
            //                 else
            //                 {
            //                     m_FieldLength.Add(".5in");
            //                     dReportWidth = dReportWidth + 0.5;
            //                 }
            //                 break;
            //             case "System.String":
            //                 SqlDataAdapter objAdapter = new SqlDataAdapter(command);
            //                 DataTable dtData = new DataTable();
            //                 objAdapter.Fill(dtData);
            //                 objAdapter.Dispose();
            //                 dtData.Dispose();
            //                 DataRow[] drr = dtTable.Select("attrib_id = '" + sColumnName + "'");
            //                 string sTemp = "";
            //                 if (drr.Length > 0)
            //                     sTemp = drr[0]["caption"].ToString();

            //                 double iLength = getColumnDataLength(dtData, sColumnName);
            //                 if (iLength < sTemp.Length)
            //                     iLength = sTemp.Length;
            //                 iLength = iLength * 0.1;
            //                 m_FieldLength.Add(iLength.ToString() + "in");
            //                 dReportWidth = dReportWidth + iLength;
            //                 iStringFields++;
            //                 break;
            //             default:
            //                 if (sColumnName.Length > 5)
            //                 {
            //                     double dTemp = sColumnName.Length * 0.1 + 0.5;
            //                     m_FieldLength.Add(dTemp.ToString() + "in");
            //                     dReportWidth = dReportWidth + dTemp;
            //                 }
            //                 else
            //                 {
            //                     m_FieldLength.Add("1in");
            //                     dReportWidth = dReportWidth + 0.5;
            //                 }
            //                 break;
            //         }
            //     }
            // }
            // ReportWidth = (float)dReportWidth;
            // HttpContext.Current.Session["ReportWidth"] = dReportWidth + iStringFields * 0.4; 
            #endregion
            m_FieldLength = new ArrayList();
            m_fields = new ArrayList();
            int iStringFields = 0;

            foreach (DataRow dr in dsInput.Tables["p_sy_report_att"].Rows)
            {
                m_fields.Add(dr["attrib_id"].ToString());
                string sLength = dr["mb_field_length"].ToString();
                if (sLength == "0") sLength = "0.5";
                if (sLength == "") sLength = "0.5";
                m_FieldLength.Add(sLength + "in");
                dReportWidth = dReportWidth + Double.Parse(sLength);
            }

            #region MyRegion
            //foreach (DataColumn dc in dsInput.Tables[dsInput.Tables.Count - 1].Columns)
            //{
            //    string sColumnName = dc.ColumnName;
            //    m_fields.Add(sColumnName);

            //    switch (dc.DataType.ToString())
            //    {
            //        case "System.Int32":
            //        case "System.Byte":
            //        case "System.Decimal":
            //            if (sColumnName.Length > 5)
            //            {
            //                double dTemp = sColumnName.Length * 0.1 + 0.5;
            //                m_FieldLength.Add(dTemp.ToString() + "in");
            //                dReportWidth = dReportWidth + dTemp;
            //            }
            //            else
            //            {
            //                m_FieldLength.Add(".5in");
            //                dReportWidth = dReportWidth + 0.5;
            //            }
            //            break;
            //        case "System.DateTime":
            //            m_DateTime.Add(sColumnName);
            //            if (sColumnName.Length > 15)
            //            {
            //                double dTemp = sColumnName.Length * 0.1;
            //                m_FieldLength.Add(dTemp.ToString() + "in");
            //                dReportWidth = dReportWidth + dTemp;
            //            }
            //            else
            //            {
            //                m_FieldLength.Add("1.7in");
            //                dReportWidth = dReportWidth + 2.1;
            //            }
            //            break;
            //        case "System.Boolean":
            //            if (sColumnName.Length > 5)
            //            {
            //                double dTemp = sColumnName.Length * 0.1;
            //                m_FieldLength.Add(dTemp.ToString() + "in");
            //                dReportWidth = dReportWidth + dTemp;
            //            }
            //            else
            //            {
            //                m_FieldLength.Add(".5in");
            //                dReportWidth = dReportWidth + 0.5;
            //            }
            //            break;
            //        case "System.String":
            //            #region MyRegion
            //            //SqlDataAdapter objAdapter = new SqlDataAdapter(command);
            //            //DataTable dtData = new DataTable();
            //            //objAdapter.Fill(dtData);
            //            //objAdapter.Dispose();
            //            //dtData.Dispose();
            //            //DataRow[] drr = dtTable.Select("attrib_id = '" + sColumnName + "'");
            //            //string sTemp = "";
            //            //if (drr.Length > 0)
            //            //    sTemp = drr[0]["caption"].ToString();

            //            //double iLength = getColumnDataLength(dtData, sColumnName);

            //            //if (iLength < sTemp.Length)
            //            //    iLength = sTemp.Length; 
            //            #endregion

            //            double iLength = 15;
            //            iLength = iLength * 0.1;
            //            m_FieldLength.Add(iLength.ToString() + "in");
            //            dReportWidth = dReportWidth + iLength;
            //            iStringFields++;
            //            break;
            //        default:
            //            if (sColumnName.Length > 5)
            //            {
            //                double dTemp = sColumnName.Length * 0.1 + 0.5;
            //                m_FieldLength.Add(dTemp.ToString() + "in");
            //                dReportWidth = dReportWidth + dTemp;
            //            }
            //            else
            //            {
            //                m_FieldLength.Add("1in");
            //                dReportWidth = dReportWidth + 0.5;
            //            }
            //            break;
            //    }
            //} 
            #endregion

            ReportWidth = (float)dReportWidth;
            if (dReportWidth > 30)
            {
                dReportWidth = 30;
                ReportWidth = 30;
            }
            HttpContext.Current.Session["ReportWidth"] = dReportWidth + iStringFields * 0.4;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("GenerateFieldsList : Error : " + Ex.Message);
            HttpContext.Current.Response.Redirect("Error.aspx?msg=" + Ex.Message, false);
        }
        return bHasRows;
    }

    private int getColumnDataLength(DataTable dt, string sColumnName)
    {
        int iReturn = 0;
        try
        {
            iReturn = sColumnName.Length;
            int iLength = sColumnName.Length;
            foreach (DataRow dr in dt.Rows)
            {
                iLength = dr[sColumnName].ToString().Length;
                if (iLength > iReturn)
                    iReturn = iLength;
                if (iReturn > 40)
                {
                    iReturn = 40;
                    break;
                }
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getColumnDataLength : Error : " + ex.Message);
            return iReturn;
        }
        return iReturn;
    }

    public void writeEndRDLC()
    {
        writer.WriteEndElement(); // Report
        // Flush the writer and close the stream
        writer.Flush();
        stream.Close();
    }


    public void writeEndRDLC(ref MemoryStream msReport, string FilePath)
    {

        writer.WriteEndElement(); // Report
        // Flush the writer and close the stream
        writer.Flush();
        stream.Close();
        //System.IO.MemoryStream msReportStream = null;
        if (File.Exists(FilePath))
        {
            System.Xml.XmlDocument xDoc = new XmlDocument();
            xDoc.Load(FilePath);
            string strRdl = xDoc.OuterXml;
            xDoc = null;
            File.Delete(FilePath);
            byte[] rdlBytes = Encoding.UTF8.GetBytes(strRdl);
            msReport = new MemoryStream(rdlBytes);
        }
    }

    public void writeInitRDLC(String absFilePath)
    {
        // Open a new RDL file stream for writing
        //stream = File.OpenWrite(absFilePath);
        stream = new FileStream(absFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
        writer = new XmlTextWriter(stream, Encoding.UTF8);

        // Causes child elements to be indented
        writer.Formatting = Formatting.Indented;

        // Report element
        writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
        writer.WriteStartElement("Report");
        writer.WriteAttributeString("xmlns", null, "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");
        writer.WriteAttributeString("xmlns:rd", null, "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
        //writer.WriteElementString("Width", "6in");
    }

    /**
     * This function writes a textbox in the RDLC file
     */
    public void writeTextBox(String name, String fieldName)
    {
        // Textbox
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, name);
        writer.WriteElementString("Left", "1in");
        writer.WriteElementString("Top", "0.42708in");
        writer.WriteElementString("rd:DefaultName", name);
        //writer.WriteElementString("HideDuplicates", "DataSet1");
        writer.WriteElementString("ZIndex", "20");
        writer.WriteElementString("Width", "2.125in");
        writer.WriteElementString("CanGrow", "true");
        writer.WriteElementString("Height", "0.19444in");
        writer.WriteElementString("Value", "=Fields!" + fieldName + ".Value");
        writer.WriteEndElement(); // Textbox
    }

    public void writeLabel(String name, String fieldName)
    {
        // Textbox
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, name);
        writer.WriteElementString("Left", "0in");
        writer.WriteElementString("Top", "0.42708in");
        writer.WriteElementString("rd:DefaultName", name);
        //writer.WriteElementString("HideDuplicates", "DataSet1");
        writer.WriteElementString("ZIndex", "20");
        writer.WriteElementString("Width", "2.125in");
        writer.WriteElementString("CanGrow", "true");
        writer.WriteElementString("Height", "0.19444in");
        writer.WriteElementString("Value", fieldName);
        writer.WriteEndElement(); // Textbox
    }

    public void writeDataSource(String name)
    {
        // DataSource element
        writer.WriteStartElement("DataSources");
        writer.WriteStartElement("DataSource");
        writer.WriteAttributeString("Name", null, name);
        writer.WriteStartElement("ConnectionProperties");
        writer.WriteElementString("DataProvider", "SQL");
        writer.WriteElementString("ConnectString", "");//writer.WriteElementString("ConnectString", m_connectionString);
        writer.WriteElementString("IntegratedSecurity", "true");
        writer.WriteEndElement(); // ConnectionProperties
        writer.WriteElementString("rd:DataSourceID", m_datasourceid);
        writer.WriteEndElement(); // DataSource
        writer.WriteEndElement(); // DataSources
    }
    public void writeColumns()
    {
        // Table Columns
        writer.WriteStartElement("TableColumns");

        //srivatsan
        writer.WriteStartElement("TableColumn");
        writer.WriteElementString("Width", "0.0in");
        writer.WriteEndElement();
        //

        for (int i = 0; i < m_fields.Count; i++)
        {

            ////srivatsan
            //writer.WriteStartElement("TableColumn");
            //writer.WriteElementString("Width", ".15in");
            //writer.WriteEndElement();
            ////



            writer.WriteStartElement("TableColumn");
            writer.WriteElementString("Width", m_FieldLength[i].ToString());
            writer.WriteEndElement(); // TableColumn
            if (i != m_fields.Count - 1)
            {
                writer.WriteStartElement("TableColumn");
                writer.WriteElementString("Width", ".15in");
                writer.WriteEndElement();
            }
        }
        writer.WriteEndElement(); // TableColumns
    }

    public void writeStyle(XmlTextWriter writer, Hashtable hsStyle)
    {
        writer.WriteStartElement("Style");
        foreach (string sKey in hsStyle.Keys)
            writer.WriteElementString(sKey, null, hsStyle[sKey].ToString());
        writer.WriteEndElement();
    }

    public void writeDetails()
    {
        // Details Row
        writer.WriteStartElement("Details");
        writer.WriteStartElement("TableRows");
        writer.WriteStartElement("TableRow");
        //writer.WriteElementString("Height", ".25in");
        writer.WriteStartElement("TableCells");

        string fieldName = "";
        //Hashtable hsStyle0 = getCSSProperies(".Grid_Row0");
        //Hashtable hsStyle1 = getCSSProperies(".Grid_Row1");
        string sBG0 = "";
        string sBG1 = "";
        string sTemp = "";

        if (ExportType == "")//modified by Nithya for Export Performance issue
        {
            sBG0 = getCSSPropertyValue(".Grid_Row0", "background-color");
            sBG1 = getCSSPropertyValue(".Grid_Row1", "background-color");
            if (sBG0 == "") sBG0 = "#FFFFFF";
            sTemp = @"=Iif(RowNumber(Nothing) Mod 2, ""Transparent" + "\", \"" + sBG1 + "\")";
        }
        else
        {
            sBG1 = "#FFFFFF";
            sTemp = @"=Iif(RowNumber(Nothing) Mod 2, ""Transparent" + "\", \"" + sBG1 + "\")";
        }

        // Added by srivatsan to create a empty column to fix firefox issue
        writer.WriteStartElement("TableCell");
        writer.WriteStartElement("ReportItems");
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, "temp_empty_column");
        writer.WriteElementString("Value", "");
        //writeStyle(writer, hsStyle);
        if (EnableHyperLink != true) //Added by 'Imran Gani' on 05-Nov-2012, to set the empty column.
        {
            writer.WriteStartElement("Visibility");
            writer.WriteElementString("Hidden", "true");
            writer.WriteEndElement();// Visibility
        }
        writer.WriteElementString("Width", "0in");
        writer.WriteElementString("CanGrow", "false");
        writer.WriteElementString("CanShrink", "true");
        writer.WriteStartElement("Style");
        writer.WriteElementString("VerticalAlign", "Middle");
        if (ExportType == "")//added by nithya for export performance issue
            writer.WriteElementString("BackgroundColor", sTemp);//writer.WriteElementString("BackgroundColor", @"=Iif(RowNumber(Nothing) Mod 2, ""White"", ""WhiteSmoke"")");
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndElement();
        //




        for (int iFieldCount = 0; iFieldCount < m_fields.Count; iFieldCount++)
        {
            /*Hashtable hsStyle;
            if (iFieldCount % 2 == 0)
                hsStyle = hsStyle0;
            else
                hsStyle = hsStyle1;*/
            fieldName = m_fields[iFieldCount].ToString();
            writer.WriteStartElement("TableCell");
            writer.WriteStartElement("ReportItems");
            // Textbox
            writer.WriteStartElement("Textbox");
            writer.WriteAttributeString("Name", null, fieldName);
            //writer.WriteElementString("HideDuplicates", "DataSet1");
            writer.WriteElementString("ZIndex", "2");

            //srivatsan
            writer.WriteElementString("CanGrow", "true");
            writer.WriteElementString("CanShrink", "true");
            //writer.WriteElementString("Width", "10in");
            //

            //if (m_DateTime.Contains(fieldName))
            //    writer.WriteElementString("Value", "=Format(Fields!" + fieldName + @".Value,""dd-MMM-yyyy hh:mm tt"")");
            //else
            writer.WriteElementString("Value", "=Fields!" + fieldName + ".Value");
            //writeStyle(writer, hsStyle);
            writer.WriteStartElement("Style");
            writer.WriteElementString("VerticalAlign", "Middle");
            writer.WriteElementString("BackgroundColor", sTemp);
            string controlFont = getCSSPropertyValue(".controlFont", "font-size");
            writer.WriteElementString("FontSize", controlFont);
            //writer.WriteElementString("FontSize", "9pt");
            writer.WriteEndElement();


            writer.WriteEndElement(); // Textbox
            writer.WriteEndElement(); // ReportItems
            writer.WriteEndElement(); // TableCell

            if (iFieldCount < m_fields.Count - 1)
            {
                writer.WriteStartElement("TableCell");
                writer.WriteStartElement("ReportItems");
                writer.WriteStartElement("Textbox");
                writer.WriteAttributeString("Name", null, "txt" + fieldName);
                writer.WriteElementString("Value", "   ");
                //writeStyle(writer, hsStyle);

                // srivatsan
                writer.WriteStartElement("Visibility");
                writer.WriteElementString("Hidden", "false");
                writer.WriteEndElement();// Visibility
                //

                writer.WriteStartElement("Style");
                writer.WriteElementString("VerticalAlign", "Middle");
                if (ExportType == "")//added by Nithya for export performance issue
                    writer.WriteElementString("BackgroundColor", sTemp);//writer.WriteElementString("BackgroundColor", @"=Iif(RowNumber(Nothing) Mod 2, ""White"", ""WhiteSmoke"")")
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

        // End Details element and children   
        writer.WriteEndElement(); // TableCells
        writer.WriteElementString("Height", "0.25in");
        writer.WriteEndElement(); // TableRow
        writer.WriteEndElement(); // TableRows
        writer.WriteEndElement(); // Details
    }

    public void writeDetails(DataSet dsReportInput)
    {
        // Details Row
        writer.WriteStartElement("Details");
        writer.WriteStartElement("TableRows");
        writer.WriteStartElement("TableRow");
        //writer.WriteElementString("Height", ".25in");
        writer.WriteStartElement("TableCells");

        string fieldName = "";
        //Hashtable hsStyle0 = getCSSProperies(".Grid_Row0");
        //Hashtable hsStyle1 = getCSSProperies(".Grid_Row1");
        string sBG0 = "";
        string sBG1 = "";
        string sTemp = "";

        if (ExportType == "")//modified by nithya for export performance issue
        {
            sBG0 = getCSSPropertyValue(".Grid_Row0", "background-color");
            sBG1 = getCSSPropertyValue(".Grid_Row1", "background-color");
            if (sBG0 == "") sBG0 = "#FFFFFF";
            sTemp = @"=Iif(RowNumber(Nothing) Mod 2, ""Transparent" + "\", \"" + sBG1 + "\")";
        }
        else
        {
            sBG1 = "#FFFFFF";
            sTemp = @"=Iif(RowNumber(Nothing) Mod 2, ""Transparent" + "\", \"" + sBG1 + "\")";
        }

        // Added by srivatsan to create a empty column to fix firefox issue
        writer.WriteStartElement("TableCell");
        writer.WriteStartElement("ReportItems");
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, "temp_empty_column");
        writer.WriteElementString("Value", "");
        //writeStyle(writer, hsStyle);
        if (EnableHyperLink != true) //Added by 'Imran Gani' on 05-Nov-2012, to set the empty column.
        {
            writer.WriteStartElement("Visibility");
            writer.WriteElementString("Hidden", "true");
            writer.WriteEndElement();// Visibility
        }
        writer.WriteElementString("Width", "0in");
        writer.WriteElementString("CanGrow", "false");
        writer.WriteElementString("CanShrink", "true");
        writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingRight", "2pt");
        writer.WriteElementString("VerticalAlign", "Middle");
        if (ExportType == "")//modified by nithya for export performance issue
            writer.WriteElementString("BackgroundColor", sTemp);//writer.WriteElementString("BackgroundColor", @"=Iif(RowNumber(Nothing) Mod 2, ""White"", ""WhiteSmoke"")");
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndElement();
        //




        for (int iFieldCount = 0; iFieldCount < m_fields.Count; iFieldCount++)
        {
            Localization ll = new Localization(); // Added by 'Imran Gani' on 09-Aug-12, for Date and Currency format.
            string strTempCol; // Added by 'Imran Gani' on 13/02/2012, for HyperLink properties setting.
            /*Hashtable hsStyle;
            if (iFieldCount % 2 == 0)
                hsStyle = hsStyle0;
            else
                hsStyle = hsStyle1;*/
            fieldName = m_fields[iFieldCount].ToString();
            writer.WriteStartElement("TableCell");
            writer.WriteStartElement("ReportItems");
            // Textbox
            writer.WriteStartElement("Textbox");
            writer.WriteAttributeString("Name", null, fieldName);
            //writer.WriteElementString("HideDuplicates", "DataSet1");
            writer.WriteElementString("ZIndex", "2");

            //srivatsan
            writer.WriteElementString("CanGrow", "true");
            writer.WriteElementString("CanShrink", "true");
            //writer.WriteElementString("TextAlign", getFieldAlignment(dsReportInput, fieldName));
            //writer.WriteElementString("Width", "10in");
            //

            //if (m_DateTime.Contains(fieldName))
            //    writer.WriteElementString("Value", "=Format(Fields!" + fieldName + @".Value,""dd-MMM-yyyy hh:mm tt"")");
            //else

            string fieldType = getFieldType(dsReportInput, fieldName);
            //if (fieldType.ToUpper() == "CU")
            //{
            //    writer.WriteElementString("Format", "$#,#00.00");
            //    writer.WriteElementString("Value", "=Fields!" + fieldName + ".Value");
            //    //writer.WriteElementString("Value", "=FormatCurrency(Fields!" + fieldName + ".Value)");
            //}
            //else if (fieldType.ToUpper() == "DC")
            //{
            //    writer.WriteElementString("Format", "#,#00.00");
            //    writer.WriteElementString("Value", "=Fields!" + fieldName + ".Value");
            //    //writer.WriteElementString("Value", "=FormatNumber(Fields!" + fieldName + @".Value,2)");
            //}
            //else 
            //if (fieldType.ToUpper() == "DA")
            //    writer.WriteElementString("Value", "=FormatDateTime(Fields!" + fieldName + @".Value,2)"); // Commanded by 'Imran Gani' on 27-Aug-12
            //else
            writer.WriteElementString("Value", "=Fields!" + fieldName + ".Value");

            if (iFieldCount == 0) // Added by 'Imran Gani' on 13/02/2012, for HyperLink properties setting.
            {
                if (EnableHyperLink == true)
                {
                    DataRow drFirstCol = dsReportInput.Tables["p_sy_report_att"].Select("attrib_sequence='0'")[0];
                    strTempCol = drFirstCol["attrib_id"].ToString() + "_" + drFirstCol["af_row_id"].ToString();

                    writer.WriteStartElement("Action");
                    writer.WriteElementString("Hyperlink", "=Fields!" + strTempCol + ".Value");
                    writer.WriteEndElement();
                }
            }
            //writeStyle(writer, hsStyle);
            writer.WriteStartElement("Style");

            if (iFieldCount == 0) // Added by 'Imran Gani' for HyperLink properties setting.
                if (EnableHyperLink == true)
                    writer.WriteElementString("TextDecoration", "Underline");

            #region Old Code commented by 'Imran Gani' on 28-Feb-2014, for locale support.
            //if (fieldType.ToUpper() == "CU")
            //{
            //    writer.WriteElementString("Language", ll.getUserCulture().ToString());
            //    writer.WriteElementString("Format", ll.getUserCurrencyCode() + " #,#.00");
            //    //writer.WriteElementString("Format", "$#,##0.00");
            //}
            //else if (fieldType.ToUpper() == "DC")
            //    writer.WriteElementString("Format", "#,##0.00");
            #endregion

            #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
            string sLocale = HttpContext.Current.Session["userlocale"].ToString();
            switch (fieldType.ToUpper())
            {
                case "CU":
                    writer.WriteElementString("Language", MBLocalization.getCultureInfo(sLocale).ToString());
                    writer.WriteElementString("Format", MBLocalization.getCurrencyCode(sLocale) + " #,#.00");
                    break;
                case "NU":
                case "AN":
                    writer.WriteElementString("Language", MBLocalization.getCultureInfo(sLocale).ToString());
                    writer.WriteElementString("Format", " #,#");
                    break;
                case "DC":
                case "FL":
                    writer.WriteElementString("Language", MBLocalization.getCultureInfo(sLocale).ToString());
                    writer.WriteElementString("Format", " #,#.00");
                    break;
            }
            #endregion

            writer.WriteElementString("PaddingRight", "2pt");
            writer.WriteElementString("VerticalAlign", "Middle");
            if (ExportType == "")//modified by nithya for export performance issue
                writer.WriteElementString("BackgroundColor", sTemp);
            writer.WriteElementString("TextAlign", getFieldAlignment(dsReportInput, fieldName));
            string controlFont = getCSSPropertyValue(".controlFont", "font-size");
            writer.WriteElementString("FontSize", controlFont);
            //writer.WriteElementString("FontSize", "9pt");
            DataRow[] drFormat = dsReportInput.Tables["p_sy_report_att"].Select("attrib_id='" + fieldName + "'");
            if (drFormat.Length > 0)
                if (drFormat[0]["is_bold"].ToString().ToLower().Equals("true"))
                    writer.WriteElementString("FontWeight", "Bold");//-------------

            writer.WriteEndElement();


            writer.WriteEndElement(); // Textbox
            writer.WriteEndElement(); // ReportItems
            writer.WriteEndElement(); // TableCell

            if (iFieldCount < m_fields.Count - 1)
            {
                writer.WriteStartElement("TableCell");
                writer.WriteStartElement("ReportItems");
                writer.WriteStartElement("Textbox");
                writer.WriteAttributeString("Name", null, "txt" + fieldName);
                writer.WriteElementString("Value", "   ");
                //writeStyle(writer, hsStyle);

                // srivatsan
                writer.WriteStartElement("Visibility");
                writer.WriteElementString("Hidden", "false");
                writer.WriteEndElement();// Visibility
                //


                writer.WriteStartElement("Style");
                writer.WriteElementString("PaddingRight", "2pt");
                writer.WriteElementString("VerticalAlign", "Middle");
                if (ExportType == "")//Modified by nithya for export performance issue
                    writer.WriteElementString("BackgroundColor", sTemp);//writer.WriteElementString("BackgroundColor", @"=Iif(RowNumber(Nothing) Mod 2, ""White"", ""WhiteSmoke"")");
                writer.WriteElementString("TextAlign", getFieldAlignment(dsReportInput, fieldName));
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

        // End Details element and children   
        writer.WriteEndElement(); // TableCells
        writer.WriteElementString("Height", "0.25in");
        writer.WriteEndElement(); // TableRow
        writer.WriteEndElement(); // TableRows
        writer.WriteEndElement(); // Details
    }

    #region "Getting Property Value From CSS"

    // Added by srivatsan to get the alignment of the fields depending on the datatype
    private string getFieldAlignment(DataSet dsReportInput, string columnname)
    {
        string align = "Left";
        try
        {
            if (dsReportInput != null)
            {
                if (dsReportInput.Tables.Count > 0)
                {
                    if (dsReportInput.Tables["Table"] != null)
                    {
                        if (dsReportInput.Tables["Table"].Columns.Count > 0)
                        {
                            DataColumn dc = dsReportInput.Tables["Table"].Columns[columnname];
                            if (dc.ExtendedProperties["DataType"] != null)
                            {
                                if (dc.ExtendedProperties["DataType"].ToString().Trim() != "")
                                {
                                    string datatype = dc.ExtendedProperties["DataType"].ToString().Trim().ToUpper();
                                    switch (datatype)
                                    {
                                        case "DA":
                                        case "DT":
                                        case "TX":
                                        case "BO":
                                            align = "Left";
                                            break;

                                        case "DC":
                                        case "NU":
                                        case "AN":
                                        case "FL":
                                        case "CU":
                                            align = "Right";
                                            break;
                                        default:
                                            align = "Left";
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    else if (dsReportInput.Tables.Contains("p_sy_report"))
                    {
                        if (dsReportInput.Tables["p_sy_report"].Rows.Count > 0)
                        {
                            if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
                                align = getAttribAlignment("object", dsReportInput, columnname);
                            else if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
                                align = getAttribAlignment("sql", dsReportInput, columnname);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getFieldAlignment :" + ex.Message);
        }
        return align;
    }

    private string getAttribAlignment(string rptSrc, DataSet dsReportInput, string columnName)
    {
        string retAlign = "Left";
        try
        {
            if (!dsReportInput.Tables.Contains("p_sy_report_att"))
                return retAlign;

            DataRow[] drF = dsReportInput.Tables["p_sy_report_att"].Select("attrib_id='" + columnName + "'");
            if (drF.Length > 0)
            {
                HDDatabase hdd = new HDDatabase();
                string retDataType = "";
                if (rptSrc.ToLower() == "object")
                {
                    string tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + drF[0]["temp_attrib_id"].ToString() + "'";

                    DataTable dtt = hdd.GetDataTable(tmpSQL);
                    if (dtt == null)
                        retDataType = "TX";
                    else
                    {
                        if (dtt.Rows.Count == 0)
                            retDataType = "TX";
                        else
                            retDataType = dtt.Rows[0]["attrib_data_type"].ToString();
                    }
                    if (retDataType.ToUpper() == "BO" || retDataType.ToUpper() == "DT" || retDataType.ToUpper() == "DA")
                        retDataType = "TX";
                    dtt = null;
                }
                else if (rptSrc.ToLower() == "sql")
                    retDataType = "TX";
                hdd = null;
                if (retDataType == "TX")
                    retAlign = "Left";
                else //CU, NU, DC
                    retAlign = "Right";
            }
            drF = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getAttribAlignment : Error : " + ex.Message);
        }
        return retAlign;
    }

    private string getFieldType(DataSet dsReportInput, string columnName)
    {
        string retDataType = "TX";
        try
        {
            if (!dsReportInput.Tables.Contains("p_sy_report_att"))
                return retDataType;
            HDDatabase hdd = new HDDatabase();
            DataRow[] drF = dsReportInput.Tables["p_sy_report_att"].Select("attrib_id='" + columnName + "'");
            if (drF.Length > 0)//sql
            {

                string tmpSQL = "";

                if (drF[0].Table.Columns.Contains("temp_attrib_id"))
                    tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + drF[0]["temp_attrib_id"].ToString() + "'";
                else
                    tmpSQL = "select attrib_data_type from sy_obj_att where attrib_id='" + drF[0]["attrib_id"].ToString() + "'";

                DataTable dtt = hdd.GetDataTable(tmpSQL);
                if (dtt == null)
                    retDataType = "TX";
                else
                {
                    if (dtt.Rows.Count == 0)
                        retDataType = "TX";
                    else
                        retDataType = dtt.Rows[0]["attrib_data_type"].ToString();
                }
                dtt = null;
            }
            else//object
            {
                string tmpSQL = "select attrib_data_type from sy_obj_att where af_row_id='" + columnName + "'";

                DataTable dtt = hdd.GetDataTable(tmpSQL);
                if (dtt == null)
                    retDataType = "TX";
                else
                {
                    if (dtt.Rows.Count == 0)
                        retDataType = "TX";
                    else
                        retDataType = dtt.Rows[0]["attrib_data_type"].ToString();
                }
                dtt = null;
            }
            drF = null;
            hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getFieldType : Error : " + ex.Message);
        }
        return retDataType;
    }

    public string getCSSContent()
    {
        string sFilePath = HttpContext.Current.Server.MapPath(".") + @"\App_Themes\" + HttpContext.Current.Session["theme"].ToString() + "\\" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "") + ".css";
        string sCSSContent = "";
        StreamReader sr;

        if (File.Exists(sFilePath))
        {
            sr = File.OpenText(sFilePath);
            sCSSContent = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
        }
        return sCSSContent;
    }

    private string getCSSClass(string CSSContent, string ClassName)
    {
        //ClassName = ClassName +"\r\n{\r\n";//ClassName = "." + ClassName + "\r\n{\r\n";
        int iStart = 0;
        int iEnd = 0;
        string sCSSClass = "";
        if (CSSContent.Contains(ClassName))
        {
            iStart = CSSContent.IndexOf(ClassName);
            iEnd = CSSContent.IndexOf("}", iStart);
            sCSSClass = CSSContent.Substring(iStart + ClassName.Length, iEnd - iStart - ClassName.Length);
        }

        return sCSSClass;
    }

    public string getCSSPropertyValue(string ClassName, string Property)
    {
        string sValue = "";
        string sCSSContent = getCSSContent();
        if (sCSSContent != "")
        {
            string sCSSClass = getCSSClass(sCSSContent, ClassName);
            if (sCSSClass != "")
            {
                int iStart = 0;
                int iEnd = 0;

                if (sCSSClass.Contains(Property))
                {
                    iStart = sCSSClass.IndexOf(Property);
                    iStart = sCSSClass.IndexOf(":", iStart);
                    iStart = iStart + 1;
                    iEnd = sCSSClass.IndexOf(";", iStart + 1);
                    sValue = sCSSClass.Substring(iStart, iEnd - iStart);
                }
            }
        }
        return sValue;
    }

    private Hashtable getCSSProperies(string ClassName)
    {
        Hashtable hsStyle = new Hashtable();

        try
        {
            string sValue = getCSSPropertyValue(ClassName, "background-color");
            if (sValue != "")
                hsStyle.Add("BackgroundColor", sValue);
            if (getCSSPropertyValue(ClassName, "FONT-WEIGHT").Trim().ToLower() == "bold")
                hsStyle.Add("FontWeight", 800);
            else
                hsStyle.Add("FontWeight", 400);
            string sFontSize = getCSSPropertyValue(ClassName, "FONT-SIZE").Trim().ToLower().Replace("px", "pt");
            if (sFontSize == "") sFontSize = "8pt";
            hsStyle.Add("FontSize", sFontSize);
            sValue = getCSSPropertyValue(ClassName, "COLOR").Trim();
            if (sValue != "")
                hsStyle.Add("Color", sValue);
            sValue = getCSSPropertyValue(ClassName, "text-align").Trim();
            if (sValue == "")
                sValue = "Center";
            else
                sValue = sValue.Substring(0, 1).ToUpper() + sValue.Substring(1, sValue.Length - 1);
            hsStyle.Add("TextAlign", sValue);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getProperties : " + ex.Message);
            hsStyle = null;
        }
        return hsStyle;
    }
    #endregion

    public void writeHeader(DataSet dsReportInput)
    {
        double dLeft = 0.5;
        double dTop = 0.0;

        // Header Row
        writer.WriteStartElement("Header");
        writer.WriteStartElement("TableRows");
        writer.WriteStartElement("TableRow");
        //writer.WriteElementString("Height", ".25in");
        writer.WriteStartElement("TableCells");
        //DataSet dsReportInput = (DataSet)HttpContext.Current.Session["ReportInput"];
        //Hashtable hsStyle = getCSSProperies(".Grid_Header");//Hashtable hsStyle = getCSSProperies(".Dynamic_PageHeaderRow");
        Hashtable hsStyle = getCSSProperies(".Grid_Report_Header");
        hsStyle.Add("VerticalAlign", "Middle");


        // Added by Srivatsan to add empty column to fix firefox display issue
        writer.WriteStartElement("TableCell");
        writer.WriteStartElement("ReportItems");

        //Added by 'Imran Gani' on 05-Nov-2012, to set the empty column.
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, "f_empty_temp_empty_column");
        writer.WriteElementString("Value", "");
        //writeStyle(writer, hsStyle);
        if (EnableHyperLink != true)
        {
            writer.WriteStartElement("Visibility");
            writer.WriteElementString("Hidden", "true");
            writer.WriteEndElement();// Visibility
        }
        writer.WriteElementString("Width", "0in");
        writer.WriteElementString("CanGrow", "false");
        writer.WriteElementString("CanShrink", "true");
        writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingRight", "0pt");
        writer.WriteElementString("VerticalAlign", "Middle");
        writer.WriteElementString("BackgroundColor", hsStyle["BackgroundColor"].ToString());//writer.WriteElementString("BackgroundColor", @"=Iif(RowNumber(Nothing) Mod 2, ""White"", ""WhiteSmoke"")");
        writer.WriteEndElement();
        writer.WriteEndElement();

        /* //Commanded by 'Imran Gani' on 05-Nov-2012.
        RDLCTextBox rdcEmpty1 = new RDLCTextBox();
        rdcEmpty1.CanGrow = false;
        rdcEmpty1.CanShrink = true;
        rdcEmpty1.Top = dTop;
        rdcEmpty1.Left = 0.0;
        rdcEmpty1.Height = 0.2;
        rdcEmpty1.Width = 0.0;
        rdcEmpty1.Style = hsStyle;
        //dLeft = dLeft + rdcEmpty1.Width;
        rdcEmpty1.Name = "f_empty_temp_empty_column";
        //rdcEmpty.Value = "   ";
        rdcEmpty1.writeElement(writer, styl);*/
        writer.WriteEndElement();
        writer.WriteEndElement();
        //




        string fieldName = "";
        for (int iFieldCount = 0; iFieldCount < m_fields.Count; iFieldCount++)
        {
            fieldName = m_fields[iFieldCount].ToString();
            writer.WriteStartElement("TableCell");
            writer.WriteStartElement("ReportItems");
            // Textbox
            RDLCTextBox rdcField = new RDLCTextBox();
            string alignment = getFieldAlignment(dsReportInput, fieldName); // srivatsan for header alignment
            if (hsStyle != null)
            {
                if (hsStyle.Contains("TextAlign"))
                {
                    hsStyle["TextAlign"] = alignment;
                    hsStyle["PaddingRight"] = "2pt";
                }
            }

            rdcField.CanGrow = true;
            //rdcField.CanShrink = true;
            rdcField.CanShrink = false;
            rdcField.Top = dTop;
            rdcField.Left = dLeft;
            rdcField.Height = 0.2;
            rdcField.Style = hsStyle;
            string sFieldName = getFieldName(dsReportInput, fieldName);
            if (sFieldName != "")
            {
                rdcField.Name = "f_" + fieldName;
                rdcField.Value = sFieldName;
                rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
                dLeft = dLeft + rdcField.Width;
            }
            else
            {
                rdcField.Name = "th_" + fieldName;
                rdcField.Value = fieldName;
                rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
                dLeft = dLeft + rdcField.Width;
            }
            rdcField.writeElement(writer, styl);
            writer.WriteEndElement();
            writer.WriteEndElement();
            if (iFieldCount != m_fields.Count - 1)
            {
                writer.WriteStartElement("TableCell");
                writer.WriteStartElement("ReportItems");
                RDLCTextBox rdcEmpty = new RDLCTextBox();
                rdcEmpty.CanGrow = true;
                rdcEmpty.CanShrink = true;
                rdcEmpty.Top = dTop;
                rdcEmpty.Left = dLeft;
                rdcEmpty.Height = 0.2;
                rdcEmpty.Width = 0.15;
                rdcEmpty.Style = hsStyle;
                dLeft = dLeft + rdcEmpty.Width;
                rdcEmpty.Name = "f_empty_" + fieldName;
                //rdcEmpty.Value = "   ";
                rdcEmpty.writeElement(writer, styl);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }
        #region MyRegion

        //foreach (string fieldName in m_fields)
        //{
        //    writer.WriteStartElement("TableCell");
        //    writer.WriteStartElement("ReportItems");

        //    // Textbox
        //    writer.WriteStartElement("Textbox");

        //    writer.WriteAttributeString("Name", null, "Header" + fieldName);

        //    /*writer.WriteStartElement("Style");
        //    writer.WriteElementString("TextDecoration", "Underline");
        //    writer.WriteEndElement(); // Style*/

        //    styl.init("RowGrouping");
        //    styl.writeRDLCStyle(writer);

        //    writer.WriteElementString("ZIndex", "5");

        //    //writer.WriteElementString("Top", "0in");
        //    //writer.WriteElementString("Left", "0in");
        //    //writer.WriteElementString("Height", ".5in");
        //    //writer.WriteElementString("Width", "1.5in");
        //    string sFieldName = getFieldName(dsReportInput, fieldName);
        //    if (sFieldName != "")
        //        writer.WriteElementString("Value", sFieldName);
        //    else
        //        writer.WriteElementString("Value", fieldName);
        //    writer.WriteEndElement(); // Textbox

        //    writer.WriteEndElement(); // ReportItems
        //    writer.WriteEndElement(); // TableCell
        //    writer.WriteStartElement("TableCell");
        //    writer.WriteStartElement("ReportItems");
        //    writer.WriteStartElement("Textbox");
        //    writer.WriteAttributeString("Name", null, "txt1" + fieldName);
        //    styl.init("RowGrouping");
        //    styl.writeRDLCStyle(writer);
        //    writer.WriteElementString("Value", "   ");
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //}

        #endregion
        writer.WriteEndElement(); // TableCells
        writer.WriteElementString("Height", "0.25in");
        writer.WriteEndElement(); // TableRow
        writer.WriteEndElement(); // TableRows
        writer.WriteElementString("RepeatOnNewPage", "true");
        writer.WriteEndElement(); // Header
    }

    private void writePageHeader()
    {
        DataSet dsReportInput = (DataSet)HttpContext.Current.Session["ReportInput"];
        double dLeft = 0.5;
        // Header Row
        writer.WriteStartElement("PageHeader");
        writer.WriteStartElement("ReportItems");
        styl.init("RowGrouping");
        foreach (string fieldName in m_fields)
        {
            // Textbox
            RDLCTextBox rdcField = new RDLCTextBox();
            rdcField.CanGrow = true;
            rdcField.CanShrink = true;
            rdcField.Top = 0.5;
            rdcField.Left = dLeft;
            rdcField.Height = 0.2;
            string sFieldName = getFieldName(dsReportInput, fieldName);
            if (sFieldName != "")
            {
                rdcField.Name = "ph_" + fieldName;
                rdcField.Value = sFieldName;
                rdcField.Width = sFieldName.Length * 0.1;
                dLeft = dLeft + rdcField.Width;
            }
            else
            {
                rdcField.Name = "ph_" + fieldName;
                rdcField.Value = fieldName;
                rdcField.Width = fieldName.Length * 0.1;
                dLeft = dLeft + rdcField.Width;
            }
            rdcField.writeElement(writer, styl);

            RDLCTextBox rdcEmpty = new RDLCTextBox();
            rdcEmpty.CanGrow = true;
            rdcEmpty.CanShrink = true;
            rdcEmpty.Top = 0.5;
            rdcEmpty.Left = dLeft;
            rdcEmpty.Height = 0.2;
            dLeft = dLeft + rdcEmpty.Width;
            rdcEmpty.Name = "ph_emp" + fieldName;
            rdcEmpty.Value = "   ";
            rdcEmpty.writeElement(writer, styl);
            #region MyRegion
            //            rdcEmpty.Width = fieldName.Length * 0.1;

            //rdcField.writeElement(writer);
            //styl.init("RowGrouping");
            //styl.writeRDLCStyle(writer);

            //writer.WriteStartElement("Textbox");
            //writer.WriteAttributeString("Name", null, "PageHeader" + fieldName);
            /*writer.WriteStartElement("Style");
            writer.WriteElementString("TextDecoration", "Underline");
            writer.WriteEndElement(); // Style*/
            //styl.init("RowGrouping");
            //styl.writeRDLCStyle(writer);

            //writer.WriteElementString("ZIndex", "5");

            //writer.WriteElementString("Top", "0in");
            //writer.WriteElementString("Left", "0in");
            //writer.WriteElementString("Height", ".5in");
            //writer.WriteElementString("Width", "1.5in");

            //string sFieldName = getFieldName(dsReportInput, fieldName);
            //if (sFieldName != "")
            //writer.WriteElementString("Value", sFieldName);
            //else
            //writer.WriteElementString("Value", fieldName);
            //writer.WriteEndElement(); // Textbox


            //writer.WriteEndElement(); // ReportItems
            //writer.WriteStartElement("ReportItems");
            //writer.WriteStartElement("Textbox");
            //writer.WriteAttributeString("Name", null, "ph_" + fieldName);
            //styl.init("RowGrouping");
            //styl.writeRDLCStyle(writer);
            //writer.WriteElementString("Value", "   ");
            //writer.WriteEndElement(); 
            #endregion
        }
        writer.WriteEndElement();
        writer.WriteElementString("Height", "0.2in");
        writer.WriteElementString("PrintOnLastPage", "true");
        writer.WriteElementString("PrintOnFirstPage", "true");
        writer.WriteEndElement(); // Header
    }

    private void writePageHeader(string ReportTitle, string ReportDesc, DataTable dtHeaderSettings)//karthik added parameter 'dtHeaderSettings' for applying settings in header like display logo, date etc.,
    {
        writer.WriteStartElement("PageHeader");
        double dLeft = 2.2; // srivatsan

        double dTop = 0.0;
        styl.init("Title");

        string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));
        writer.WriteStartElement("ReportItems");
        if ((dtHeaderSettings.Rows.Count > 0) && (dtHeaderSettings.Rows[0]["rpt_logo"].ToString().ToLower().Equals("true")))
        {


            string customlogo = getLogo();
            if (customlogo.Trim() != "")
            {
                sTemp = sTemp + "/" + customlogo;
            }
            else
            {
                sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");
                sTemp = sTemp + "/logo.gif";
            }
            //string sVal = sTemp + "/logo.gif";
            string sVal = "";

            sVal = sTemp;

            RDLCImage rImg = new RDLCImage();
            rImg.Left = 0.0;
            rImg.Height = 0.79167;
            rImg.Value = sVal;
            rImg.writeElement(writer);
            dTop = dTop + 0.1;
            //added this line for logo overlap by Sampath on 03/02/11
            dLeft = rImg.Width + 1;
        }
        RDLCTextBox rdcRH = new RDLCTextBox();
        rdcRH.CanGrow = false;
        rdcRH.CanShrink = false;
        if (ReportDesc == "")
            dTop = dTop + 0.2;
        rdcRH.Top = dTop;
        rdcRH.Left = dLeft;
        rdcRH.Height = 0.3;
        rdcRH.Width = ReportTitle.Length * 0.15;
        //dLeft = dLeft + rdcEmpty.Width;
        rdcRH.Name = "f_RH";
        rdcRH.Value = ReportTitle;
        rdcRH.writeElement(writer, styl);
        //commented:Date at footer only,
        //RDLCTextBox rdcPN = new RDLCTextBox();
        //rdcPN.Name = "PN";
        //rdcPN.CanGrow = true;
        //rdcPN.CanShrink = true;
        //rdcPN.Top = dTop;
        //double dTemp = 0;
        //for (int iCount = 0; iCount < m_FieldLength.Count; iCount++)
        //{
        //    dTemp = dTemp + double.Parse(m_FieldLength[iCount].ToString().Replace("in",""));
        //}
        //if (dTemp > 1)
        //{
        //    rdcPN.Left = dTemp - 1;
        //}
        //rdcPN.Height = 0.21;
        //rdcPN.Width = 2;
        //Localization li = new Localization();
        //DynamicDisplayI DDI = new DynamicDisplayI();
        //string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
        //DDI = null;
        //string sValue = li.getDateTime4TimeZone(System.DateTime.Now.ToUniversalTime().ToString(), sUTC_Offset, false, true);
        ////string sFormat = li.getDateTimeFormat();
        ////li = null;
        ////DateTime dtUser = new DateTime();
        ////dtUser = DateTime.Parse(sValue);
        ////rdcPN.Value = "Date : " + sValue;
        ////rdcPN.Value = "Date : " + dtUser.ToString(sFormat);
        //rdcPN.Value = "Date : " + sValue;
        //rdcPN.writeElement(writer);

        dTop = dTop + 0.4;
        dTop = dTop + 0.02;
        if (ReportDesc != "")
        {
            styl.init("Description");
            RDLCTextBox rdcRD = new RDLCTextBox();
            rdcRD.CanGrow = true;
            rdcRD.CanShrink = true;
            rdcRD.Top = dTop;
            rdcRD.Left = dLeft;
            rdcRD.Height = 0.3;
            rdcRD.Width = dReportWidth + 0.2;// -dLeft;
            //dLeft = dLeft + rdcEmpty.Width;
            rdcRD.Name = "f_RD";
            rdcRD.Value = ReportDesc;
            rdcRD.writeElement(writer, styl);
            dTop = dTop + rdcRD.Height;
            dTop = dTop + 0.02;
        }
        styl.init("RowGrouping");
        #region MyRegion
        //string fieldName = "";
        ////dTop = dTop / 2;
        //for (int iFieldCount = 0; iFieldCount < m_fields.Count; iFieldCount++)
        //{
        //    fieldName = m_fields[iFieldCount].ToString();
        //    // Textbox
        //    RDLCTextBox rdcField = new RDLCTextBox();
        //    rdcField.CanGrow = true;
        //    rdcField.CanShrink = true;
        //    rdcField.Top = dTop;
        //    rdcField.Left = dLeft;
        //    rdcField.Height = 0.2;
        //    string sFieldName = getFieldName(dsReportInput, fieldName);
        //    if (sFieldName != "")
        //    {
        //        rdcField.Name = "f_" + fieldName;
        //        rdcField.Value = sFieldName;
        //        rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
        //        dLeft = dLeft + rdcField.Width;
        //    }
        //    else
        //    {
        //        rdcField.Name = "ph_" + fieldName;
        //        rdcField.Value = fieldName;
        //        rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
        //        dLeft = dLeft + rdcField.Width;
        //    }
        //    rdcField.writeElement(writer, styl);
        //    if (iFieldCount != m_fields.Count - 1)
        //    {
        //        RDLCTextBox rdcEmpty = new RDLCTextBox();
        //        rdcEmpty.CanGrow = true;
        //        rdcEmpty.CanShrink = true;
        //        rdcEmpty.Top = dTop;
        //        rdcEmpty.Left = dLeft;
        //        rdcEmpty.Height = 0.2;
        //        rdcEmpty.Width = 0.15;
        //        dLeft = dLeft + rdcEmpty.Width;
        //        rdcEmpty.Name = "f_empty_" + fieldName;
        //        //rdcEmpty.Value = "   ";
        //        rdcEmpty.writeElement(writer, styl);
        //    }
        //} 
        #endregion

        dTop = dTop + 0.2;
        writer.WriteEndElement();
        writer.WriteElementString("Height", "1in");
        writer.WriteElementString("PrintOnLastPage", "true");
        writer.WriteElementString("PrintOnFirstPage", "true");
        writer.WriteEndElement();
    }

    private void writePageFooter(DataTable dtHeaderSettings)
    {
        writer.WriteStartElement("PageFooter");
        writer.WriteElementString("PrintOnFirstPage", "true");
        bool bHasItems = false;
        //code modified by Sampath
        if (dtHeaderSettings.Rows.Count > 0)
        {
            if ((dtHeaderSettings.Rows[0]["rpt_page_no"].ToString().ToLower().Equals("true")) || (dtHeaderSettings.Rows[0]["rpt_Date"].ToString().ToLower().Equals("true")) || (dtHeaderSettings.Rows[0]["rpt_foot_text"].ToString().ToLower().Trim() != ""))
                bHasItems = true;
        }
        if (bHasItems)
        {
            writer.WriteStartElement("ReportItems");
        }
        if (dtHeaderSettings.Rows.Count > 0)
        {
            if (dtHeaderSettings.Rows[0]["rpt_page_no"].ToString().ToLower().Equals("true"))
            {
                RDLCTextBox rdlctxtbox = new RDLCTextBox();
                rdlctxtbox.Name = "F_pg_no";
                rdlctxtbox.Value = "=\"Page \" & Globals!PageNumber & \" of \" & Globals!TotalPages";
                Hashtable hsStyle = new Hashtable();
                hsStyle.Add("FontSize", "8pt");
                hsStyle.Add("TextAlign", "Right");
                rdlctxtbox.Style = hsStyle;
                //rdlctxtbox.Left = (m_fields.Count * 1.5) / 2;
                rdlctxtbox.CanGrow = true; // srivatsan
                rdlctxtbox.Width = 0.9;
                rdlctxtbox.Height = 0.1;
                //rdlctxtbox.Width = 100;//srivatsan
                //double dwidth = m_fields.Count * 1.5 * 2;//srivatsan
                //if (dwidth > 50)
                //{
                //dwidth = 30;
                //}
                //rdlctxtbox.Width = dwidth;
                //double expwidth = dwidth;
                //if (dwidth < 30)
                //{
                //    if (dwidth > 10)
                //    {
                //        expwidth = dwidth / 1.5;
                //    }
                //}

                //HttpContext.Current.Session["ReportWidth"] = expwidth;
                rdlctxtbox.writeElement(writer);
            }
        //}
        //if (dtHeaderSettings.Rows.Count > 0)
        //{
            if (dtHeaderSettings.Rows[0]["rpt_Date"].ToString().ToLower().Equals("true"))
            {
                RDLCTextBox rdlctxtboxFDate = new RDLCTextBox();
                rdlctxtboxFDate.Name = "F_Date";
                Hashtable hsStyle = new Hashtable();
                hsStyle.Add("FontSize", "8pt");
                hsStyle.Add("TextAlign", "Right");
                rdlctxtboxFDate.Style = hsStyle;

                Localization li = new Localization();
                DynamicDisplayI DDI = new DynamicDisplayI();
                string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
                DDI = null;
                string sValue = li.getDateTime4TimeZone(System.DateTime.Now.ToUniversalTime().ToString(), sUTC_Offset, false, true);
                //string sFormat = li.getDateTimeFormat();
                //li = null;
                //DateTime dtUser = new DateTime();
                //dtUser = DateTime.Parse(sValue);
                //rdcPN.Value = "Date : " + sValue;
                //rdcPN.Value = "Date : " + dtUser.ToString(sFormat);
                rdlctxtboxFDate.Value = "Date : " + sValue;
                rdlctxtboxFDate.Left = (m_fields.Count * 0.8) / 2;//1.5
                rdlctxtboxFDate.CanGrow = true; // srivatsan
                rdlctxtboxFDate.Width = sValue.Length * 0.25; //0.9;//0.5
                rdlctxtboxFDate.Height = 0.1;
                ////rdlctxtbox.Width = 100;//srivatsan
                //double dwidth = m_fields.Count * 1.5 * 2;//srivatsan
                //if (dwidth > 50)
                //{
                //    dwidth = 30;
                //}
                //rdlctxtbox.Width = dwidth;
                //double expwidth = dwidth;
                //if (dwidth < 30)
                //{
                //    if (dwidth > 10)
                //    {
                //        expwidth = dwidth / 1.5;
                //    }
                //}

                //HttpContext.Current.Session["ReportWidth"] = expwidth;
                rdlctxtboxFDate.writeElement(writer);
            }
        //}

        //karthik for Footer Text
        //if (dtHeaderSettings.Rows.Count > 0)
        //{
            if (dtHeaderSettings.Rows[0]["rpt_foot_text"].ToString().Trim() != "")
            {
                RDLCTextBox rdlctxtboxFText = new RDLCTextBox();
                rdlctxtboxFText.Name = "F_Text";
                Hashtable hsStyle = new Hashtable();
                hsStyle.Add("FontSize", "8pt");
                hsStyle.Add("TextAlign", "Right");
                rdlctxtboxFText.Style = hsStyle;

                string sValue = dtHeaderSettings.Rows[0]["rpt_foot_text"].ToString();
                rdlctxtboxFText.Value = sValue;
                rdlctxtboxFText.Left = m_fields.Count / 2;
                rdlctxtboxFText.Width = sValue.Length * 0.1; //0.9;
                rdlctxtboxFText.Height = 0.1;
                rdlctxtboxFText.writeElement(writer);
            }
        }


        if (bHasItems)
        {
            writer.WriteEndElement();//ReportItems
        }
        writer.WriteElementString("Height", "0.125in");
        writer.WriteElementString("PrintOnLastPage", "true");
        writer.WriteEndElement();
    }

    private string getFieldName(DataSet dsReportInput, string FieldId)
    {
        string sFieldName = "";
        string sReportId = dsReportInput.Tables["p_sy_report"].Rows[0]["af_row_id"].ToString();
        DataRow[] dr = dsReportInput.Tables["p_sy_report_att"].Select("rpt_id = '" + sReportId.Replace("'", "''") + "' and attrib_id = '" + FieldId.Replace("'", "''") + "'");
        if (dr.Length > 0)
        {
            sFieldName = dr[0]["caption"].ToString();
        }
        return sFieldName;
    }

    public void writeDataset(DataSet dsReport)
    {
        // DataSet element
        writer.WriteStartElement("DataSets");
        writer.WriteStartElement("DataSet");
        writer.WriteAttributeString("Name", null, "DataSet1");

        // Query element
        writer.WriteStartElement("Query");
        writer.WriteElementString("DataSourceName", "DataSource1");
        //writer.WriteElementString("CommandType", "Text");
        writer.WriteElementString("CommandText", "");//writer.WriteElementString("CommandText", m_commandText);
        //writer.WriteElementString("Timeout", "30");
        writer.WriteEndElement(); // Query

        // Fields elements
        writer.WriteStartElement("Fields");
        foreach (string fieldName in m_fields)
        {
            writer.WriteStartElement("Field");
            writer.WriteAttributeString("Name", null, fieldName);
            writer.WriteElementString("DataField", null, fieldName);
            writer.WriteEndElement(); // Field
        }
        if (EnableHyperLink == true) //Added by 'Imran Gani' on 10/02/2012, for HyperLink requirement.
        {
            DataRow drFirstCol = dsReport.Tables["p_sy_report_att"].Select("attrib_sequence='0'")[0];
            string strTempCol = drFirstCol["attrib_id"].ToString() + "_" + drFirstCol["af_row_id"].ToString();
            writer.WriteStartElement("Field");
            writer.WriteAttributeString("Name", null, strTempCol);
            writer.WriteElementString("DataField", null, strTempCol);
            writer.WriteEndElement(); // Field
        }
        // End previous elements
        writer.WriteEndElement(); // Fields
        writer.WriteEndElement(); // DataSet
        writer.WriteEndElement(); // DataSets
    }

    public void writeGrouping(String name, String fieldName)
    {
        writer.WriteStartElement("Grouping");
        writer.WriteAttributeString("Name", name);
        writer.WriteElementString("PageBreakAtEnd", "true");
        writer.WriteStartElement("GroupExpressions");
        writer.WriteElementString("GroupExpression", "=Fields!" + fieldName + ".Value");
        //writer.WriteEndElement();//GroupExpression
        writer.WriteEndElement();//GroupExpressions
        writer.WriteEndElement();//Grouping
    }

    public void writeReportParameter()
    {
        writer.WriteElementString("rd:DrawGrid", "true");
        writer.WriteElementString("InteractiveWidth", "11in");
        writer.WriteElementString("rd:SnapToGrid", "true");
        writer.WriteElementString("Width", "6in");
        writer.WriteElementString("InteractiveHeight", "8.5in");
        writer.WriteElementString("rd:ReportID", m_reportid);
    }

    public void writeNoRecordsFooter()
    {
        writer.WriteStartElement("PageFooter");
        writer.WriteStartElement("Table");
        writer.WriteStartElement("Footer");
        writer.WriteAttributeString("Name", null, "tblFooter");
        writer.WriteStartElement("TableRows");
        writer.WriteStartElement("TableRow");
        writer.WriteStartElement("TableCells");

        writer.WriteStartElement("TableCell");
        writer.WriteStartElement("ReportItems");

        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, "txtNoRecords");
        writer.WriteElementString("Value", "The report you requested returns no records to be displayed");

        writer.WriteEndElement(); // Textbox
        writer.WriteEndElement(); // ReportItems
        writer.WriteEndElement(); // TableCell

        writer.WriteEndElement(); // TableCells
        writer.WriteElementString("Height", "0.25in");
        writer.WriteEndElement(); // TableRow
        writer.WriteEndElement(); // TableRows
        writer.WriteEndElement(); //Footer
        writer.WriteEndElement(); // Table
        writer.WriteEndElement();
    }

    public void GenerateMatrixRdl(String absFilePath)
    {
        //writeInitRDLC(absFilePath);
        //writeDataSource("DataSource1");

        /*writer.WriteElementString("BottomMargin", "1in");
        writer.WriteElementString("RightMargin", "1in");

        writer.WriteElementString("rd:DrawGrid", "true");
        writer.WriteElementString("InteractiveWidth", "8.5in");
        writer.WriteElementString("rd:SnapToGrid", "true");*/

        // Body element
        writer.WriteStartElement("Body");
        //writer.WriteElementString("Height", "5in");

        // ReportItems element
        writer.WriteStartElement("ReportItems");

        // Table element
        writer.WriteStartElement("Matrix");
        writer.WriteAttributeString("Name", null, "matrix1");
        writer.WriteStartElement("MatrixColumns");
        writer.WriteStartElement("MatrixColumn");
        writer.WriteElementString("Width", "2.1875in");
        writer.WriteEndElement();//MatrixColumn
        writer.WriteEndElement();//MatrixColumns
        writer.WriteElementString("NoRows", "50");
        writer.WriteElementString("Left", "0.5in");

        writeRowGroupings();

        writeCoumnGroupings();

        writer.WriteElementString("Top", "0.375in");
        writer.WriteElementString("Width", "4.375in");

        writeCorner("textbox1", "", 3);

        writer.WriteElementString("Height", "1in");

        //writeMatrixRow();
        writeMatrixRow("textbox4", "=Fields!attrib_id.Value");


        writer.WriteEndElement();//Matrix
        writer.WriteEndElement();//ReportItems

        writer.WriteElementString("Height", "1in");

        //string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));
        //sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");

        //writer.WriteStartElement("BackgroundImage");
        //writer.WriteElementString("Value", null, sTemp + "/bg.jpg");
        //writer.WriteElementString("Source", null, "External");
        //writer.WriteEndElement();

        writer.WriteEndElement();

        writer.WriteEndElement();//Body

        #region MyRegion
        //writer.WriteElementString("rd:ReportID", m_reportid);

        //writeDataset();

        //writer.WriteElementString("LeftMargin", "1in");

        /*// DataSet element
        writer.WriteStartElement("DataSets");
        writer.WriteStartElement("DataSet");
        writer.WriteAttributeString("Name", null, "DataSet1");

        // Query element
        writer.WriteStartElement("Query");
        writer.WriteElementString("DataSourceName", "DataSource1");
        //writer.WriteElementString("CommandType", "Text");
        writer.WriteElementString("CommandText", m_commandText);
        writer.WriteElementString("Timeout", "30");
        writer.WriteEndElement(); // Query*/

        /*writer.WriteElementString("Width", "6.5in");
        writer.WriteElementString("InteractiveHeight", "11in");
        writer.WriteElementString("Language", "en-US");
        writer.WriteElementString("TopMargin", "1in");*/

        /*   writer.WriteEndElement();//Report

           // Flush the writer and close the stream
           writer.Flush();
           stream.Close();*/
        //writeEndRDLC(); 
        #endregion
    }

    public void GenerateMasterDetailRdl(String absFilePath)
    {
        // Body element
        writer.WriteStartElement("Body");

        // ReportItems element
        writer.WriteStartElement("ReportItems");

        writer.WriteStartElement("List");
        writer.WriteAttributeString("Name", "list1");
        writer.WriteElementString("Left", "0.125in");

        writer.WriteStartElement("ReportItems");
        writeTextBox("Cust_1", "Cust_ID");

        writeLabel("Customer_1", "Customer ID");

        // Table element
        writer.WriteStartElement("Table");
        writer.WriteAttributeString("Name", null, "Table1");
        writer.WriteElementString("Left", "0.5in");
        writer.WriteElementString("DataSetName", "DataSet1");
        writer.WriteElementString("Top", "0.5in");
        writer.WriteElementString("Width", (m_fields.Count * 1.5) + "in");
        //writer.WriteElementString("Height", ".5in");

        writeDetails();

        //writeHeader(); 

        writeColumns();

        // End table element and end report definition file
        writer.WriteEndElement(); // Table



        writer.WriteEndElement(); // ReportItems

        writeGrouping("list1_Details_Group", "Cust_ID");
        writer.WriteEndElement();//List

        writer.WriteEndElement();//ReportItem

        writer.WriteElementString("Height", "5in");
        writer.WriteEndElement(); // Body
    }

    public void GenerateRdl(String absFilePath)
    {
        // Body element
        writer.WriteStartElement("Body");
        //writer.WriteElementString("Height", "5in");
        // ReportItems element
        writer.WriteStartElement("ReportItems");

        RDLCTextBox rtb = new RDLCTextBox();
        rtb.Name = "ReportHeader";
        rtb.Width = 10;
        rtb.Value = "This is My Report Header";
        rtb.writeElement(writer);

        // Table element
        writer.WriteStartElement("Table");
        writer.WriteAttributeString("Name", null, "Table1");
        writer.WriteElementString("Left", "0.5in");
        writer.WriteElementString("DataSetName", "DataSet1");
        writer.WriteElementString("Top", "0in");
        writer.WriteElementString("Width", (m_fields.Count * 1.5) + "in");
        //writer.WriteElementString("Height", ".5in");

        writeDetails();

        //        writeHeader();

        writeColumns();

        // End table element and end report definition file
        writer.WriteEndElement(); // Table
        writer.WriteEndElement(); // ReportItems
        //writer.WriteElementString("Height", "5in");

        //string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));
        //sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");

        /*writer.WriteStartElement("Style");
        //writer.WriteStartElement("BackgroundImage");
        //writer.WriteElementString("Value", null, sTemp + "/bg.jpg");
        //writer.WriteElementString("Source", null, "External");
        //writer.WriteEndElement();
        writer.WriteElementString("BackgroundColor", null, getCSSPropertyValue("body","background-color").Trim());
        
        writer.WriteEndElement();*/

        writer.WriteEndElement(); // Body
    }

    private void writeTableStyle()
    {
        string sBorderClr = getCSSPropertyValue(".Grid_Header", "background-color");
        writer.WriteStartElement("Style");
        writer.WriteStartElement("BorderStyle");
        writer.WriteElementString("Default", null, "Solid");
        writer.WriteEndElement();
        writer.WriteStartElement("BorderColor");
        writer.WriteElementString("Default", null, sBorderClr);
        writer.WriteEndElement();
        writer.WriteEndElement();
    }

    public void GenerateRdl(string absFilePath, string ReportName, string ReportDesc, DataSet dsReportInput)
    {
        // Body element
        writer.WriteStartElement("Body");
        //added by Sampath for background
        writer.WriteStartElement("Style");
        writer.WriteElementString("BackgroundColor", "#FFFFFF");
        writer.WriteEndElement();
        //writer.WriteElementString("Height", "5in");
        // ReportItems element
        writer.WriteStartElement("ReportItems");

        /*RDLCTextBox rtb = new RDLCTextBox();
        rtb.Name = "ReportHeader";
        rtb.Width = 15;
        rtb.Height = 0.2;
        rtb.Left = 0;
        rtb.Top = 0.1;
        rtb.CanGrow = true;
        rtb.Value = ReportName;
        rtb.writeElement(writer);

        RDLCTextBox rtb1 = new RDLCTextBox();
        rtb1.Name = "ReportDesc";
        rtb1.Width = 15;
        rtb1.Height = 0.2;
        rtb1.Left = 0;
        rtb1.Top = 0.2;
        rtb1.CanGrow = true;
        rtb1.Value = ReportDesc;
        rtb1.writeElement(writer);*/

        // Table element
        writer.WriteStartElement("Table");
        writer.WriteAttributeString("Name", null, "Table1");
        writer.WriteElementString("Left", "0.0in");
        //writer.WriteElementString("Left", "0.5in");
        writer.WriteElementString("DataSetName", "DataSet1");
        writer.WriteElementString("Top", "0in");
        writer.WriteElementString("Width", (m_fields.Count * 1.5) + "in");

        writeGrouping(dsReportInput);


        writeDetails(dsReportInput); // modified by srivatsan for Report data alignment

        writeHeader(dsReportInput);
        writeFooter(dsReportInput);
        writeColumns();

        writeTableStyle();

        // End table element and end report definition file
        writer.WriteEndElement(); // Table
        writer.WriteEndElement(); // ReportItems
        writer.WriteElementString("Height", "5in");
        //writeNoRecordsFooter();

        //string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));
        //sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");

        //writer.WriteStartElement("Style");
        //writer.WriteStartElement("BackgroundImage");
        //writer.WriteElementString("Value", null, sTemp + "/bg.jpg");
        //writer.WriteElementString("Source", null, "External");
        //writer.WriteEndElement();
        //writer.WriteElementString("BackgroundColor", null, getCSSPropertyValue("body", "background-color").Trim());
        //writer.WriteEndElement();
        writer.WriteEndElement(); // Body
        if (dsReportInput.Tables["p_report_header_footer"] != null) //Modified By Dhanapal On Dec 10 2010
        {
            writePageHeader(ReportName, ReportDesc, dsReportInput.Tables["p_report_header_footer"]);
            writePageFooter(dsReportInput.Tables["p_report_header_footer"]);
        }
        else
        {
            writePageHeader(ReportName, ReportDesc);
            writePageFooter();
        }
    }

    private void writePageHeader(string ReportTitle, string ReportDesc)
    {
        writer.WriteStartElement("PageHeader");
        writer.WriteStartElement("ReportItems");
        double dLeft = 2.2; // srivatsan

        double dTop = 0.0;
        styl.init("Title");

        string sTemp = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/"));

        string customlogo = getLogo();
        if (customlogo.Trim() != "")
        {
            sTemp = sTemp + "/" + customlogo;
        }
        else
        {
            sTemp = sTemp + "/images/" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "");
            sTemp = sTemp + "/logo.gif";
        }
        //string sVal = sTemp + "/logo.gif";
        string sVal = sTemp;
        RDLCImage rImg = new RDLCImage();
        rImg.Left = 0.0;
        rImg.Height = 0.79167;
        rImg.Value = sVal;
        rImg.writeElement(writer);
        dTop = dTop + 0.1;
        //added this line for logo overlap by Sampath on 03/02/11
        dLeft = rImg.Width + 0.75;
        RDLCTextBox rdcRH = new RDLCTextBox();
        rdcRH.CanGrow = true;
        rdcRH.CanShrink = true;
        if (ReportDesc == "")
            dTop = dTop + 0.2;
        rdcRH.Top = dTop;
        rdcRH.Left = dLeft;
        rdcRH.Height = 0.3;
        rdcRH.Width = ReportTitle.Length * 0.2;
        //dLeft = dLeft + rdcEmpty.Width;
        rdcRH.Name = "f_RH";
        rdcRH.Value = ReportTitle;
        rdcRH.writeElement(writer, styl);
        RDLCTextBox rdcPN = new RDLCTextBox();
        rdcPN.Name = "PN";
        rdcPN.CanGrow = true;
        rdcPN.CanShrink = true;
        rdcPN.Top = dTop;
        double dTemp = 0;
        for (int iCount = 0; iCount < m_FieldLength.Count; iCount++)
        {
            dTemp = dTemp + double.Parse(m_FieldLength[iCount].ToString().Replace("in", ""));
        }
        if (dTemp > 1)
        {
            rdcPN.Left = dTemp - 1;
        }
        rdcPN.Height = 0.21;
        rdcPN.Width = 2;
        Localization li = new Localization();
        DynamicDisplayI DDI = new DynamicDisplayI();
        string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
        DDI = null;
        string sValue = li.getDateTime4TimeZone(System.DateTime.Now.ToUniversalTime().ToString(), sUTC_Offset, false, true);
        //string sFormat = li.getDateTimeFormat();
        //li = null;
        //DateTime dtUser = new DateTime();
        //dtUser = DateTime.Parse(sValue);
        //rdcPN.Value = "Date : " + sValue;
        //rdcPN.Value = "Date : " + dtUser.ToString(sFormat);
        rdcPN.Value = "Date : " + sValue;
        rdcPN.writeElement(writer);
        dTop = dTop + 0.4;
        dTop = dTop + 0.02;
        if (ReportDesc != "")
        {
            styl.init("Description");
            RDLCTextBox rdcRD = new RDLCTextBox();
            rdcRD.CanGrow = true;
            rdcRD.CanShrink = true;
            rdcRD.Top = dTop;
            rdcRD.Left = dLeft;
            rdcRD.Height = 0.3;
            rdcRD.Width = dReportWidth + 0.2;// -dLeft;
            //dLeft = dLeft + rdcEmpty.Width;
            rdcRD.Name = "f_RD";
            rdcRD.Value = ReportDesc;
            rdcRD.writeElement(writer, styl);
            dTop = dTop + rdcRD.Height;
            dTop = dTop + 0.02;
        }
        styl.init("RowGrouping");
        #region MyRegion
        //string fieldName = "";
        ////dTop = dTop / 2;
        //for (int iFieldCount = 0; iFieldCount < m_fields.Count; iFieldCount++)
        //{
        //    fieldName = m_fields[iFieldCount].ToString();
        //    // Textbox
        //    RDLCTextBox rdcField = new RDLCTextBox();
        //    rdcField.CanGrow = true;
        //    rdcField.CanShrink = true;
        //    rdcField.Top = dTop;
        //    rdcField.Left = dLeft;
        //    rdcField.Height = 0.2;
        //    string sFieldName = getFieldName(dsReportInput, fieldName);
        //    if (sFieldName != "")
        //    {
        //        rdcField.Name = "f_" + fieldName;
        //        rdcField.Value = sFieldName;
        //        rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
        //        dLeft = dLeft + rdcField.Width;
        //    }
        //    else
        //    {
        //        rdcField.Name = "ph_" + fieldName;
        //        rdcField.Value = fieldName;
        //        rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
        //        dLeft = dLeft + rdcField.Width;
        //    }
        //    rdcField.writeElement(writer, styl);
        //    if (iFieldCount != m_fields.Count - 1)
        //    {
        //        RDLCTextBox rdcEmpty = new RDLCTextBox();
        //        rdcEmpty.CanGrow = true;
        //        rdcEmpty.CanShrink = true;
        //        rdcEmpty.Top = dTop;
        //        rdcEmpty.Left = dLeft;
        //        rdcEmpty.Height = 0.2;
        //        rdcEmpty.Width = 0.15;
        //        dLeft = dLeft + rdcEmpty.Width;
        //        rdcEmpty.Name = "f_empty_" + fieldName;
        //        //rdcEmpty.Value = "   ";
        //        rdcEmpty.writeElement(writer, styl);
        //    }
        //} 
        #endregion

        dTop = dTop + 0.2;
        writer.WriteEndElement();
        writer.WriteElementString("Height", "1in");
        writer.WriteElementString("PrintOnLastPage", "true");
        writer.WriteElementString("PrintOnFirstPage", "true");
        writer.WriteEndElement();
    }

    private void writePageFooter()
    {
        writer.WriteStartElement("PageFooter");
        writer.WriteElementString("PrintOnFirstPage", "true");
        writer.WriteStartElement("ReportItems");
        RDLCTextBox rdlctxtbox = new RDLCTextBox();
        rdlctxtbox.Value = "=\"Page \" & Globals!PageNumber & \" of \" & Globals!TotalPages";
        Hashtable hsStyle = new Hashtable();
        hsStyle.Add("FontSize", "8pt");
        hsStyle.Add("TextAlign", "Right");
        rdlctxtbox.Style = hsStyle;
        rdlctxtbox.Left = (m_fields.Count * 1.5) / 2;
        rdlctxtbox.CanGrow = false; // srivatsan
        rdlctxtbox.Width = 0.9;
        //rdlctxtbox.Width = 100;//srivatsan
        double dwidth = m_fields.Count * 1.5 * 2;//srivatsan
        if (dwidth > 50)
        {
            dwidth = 30;
        }
        rdlctxtbox.Width = dwidth;
        double expwidth = dwidth;
        if (dwidth < 30)
        {
            if (dwidth > 10)
            {
                expwidth = dwidth / 1.5;
            }
        }

        HttpContext.Current.Session["ReportWidth"] = expwidth;
        rdlctxtbox.writeElement(writer);

        writer.WriteEndElement();
        writer.WriteElementString("Height", "0.125in");
        writer.WriteElementString("PrintOnLastPage", "true");
        writer.WriteEndElement();
    }

    private void writeFooter(DataSet dsReportInput)//-->Added during report designer control change
    {
        Localization ll = new Localization(); // Added by 'Imran Gani' on 24-Aug-12, for currency format.
        //Modified BY Dhanapal On Dec 10 2010
        if (dsReportInput.Tables["p_report_grouping_grand_total"] == null || dsReportInput.Tables["p_report_grouping_grand_total"].Rows.Count == 0)
            return;
        ArrayList strGTotalField = new ArrayList();
        //string strGTotalField = dsReportInput.Tables["p_report_grouping_grand_total"].Rows[0]["grand_total_field"].ToString();
        foreach (DataRow drGtotal in dsReportInput.Tables["p_report_grouping_grand_total"].Rows)
        {
            if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
                strGTotalField.Add(drGtotal["grand_total_field"].ToString());
            else
                strGTotalField.Add(getColumnName(drGtotal["grand_total_field"].ToString()));
        }
        //strGTotalField = getColumnName(strGTotalField);

        double dLeft = 0.5;
        double dTop = 0.0;

        // Footer Row
        writer.WriteStartElement("Footer");
        writer.WriteStartElement("TableRows");
        writer.WriteStartElement("TableRow");
        writer.WriteStartElement("TableCells");
        Hashtable hsStyle = getCSSProperies(".Grid_Report_Header");
        hsStyle.Add("VerticalAlign", "Middle");


        // Added by Srivatsan to add empty column to fix firefox display issue
        writer.WriteStartElement("TableCell");
        writer.WriteStartElement("ReportItems");

        //Added by 'Imran Gani' on 05-Nov-2012, to set the empty column.
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", null, "f_empty_temp_empty_column_Footer");
        writer.WriteElementString("Value", "");
        //writeStyle(writer, hsStyle);
        if (EnableHyperLink != true)
        {
            writer.WriteStartElement("Visibility");
            writer.WriteElementString("Hidden", "true");
            writer.WriteEndElement();// Visibility
        }
        writer.WriteElementString("Width", "0in");
        writer.WriteElementString("CanGrow", "false");
        writer.WriteElementString("CanShrink", "true");
        writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingRight", "0pt");
        writer.WriteElementString("VerticalAlign", "Middle");
        writer.WriteElementString("BackgroundColor", hsStyle["BackgroundColor"].ToString());//writer.WriteElementString("BackgroundColor", @"=Iif(RowNumber(Nothing) Mod 2, ""White"", ""WhiteSmoke"")");
        writer.WriteEndElement();
        writer.WriteEndElement();

        /* //Commanded  by 'Imran Gani' on 05-Nov-2012.
        RDLCTextBox rdcEmpty1 = new RDLCTextBox();
        rdcEmpty1.CanGrow = false;
        rdcEmpty1.CanShrink = true;
        rdcEmpty1.Top = dTop;
        rdcEmpty1.Left = 0.0;
        rdcEmpty1.Height = 0.2;
        rdcEmpty1.Width = 0.0;
        rdcEmpty1.Style = hsStyle;
        //dLeft = dLeft + rdcEmpty1.Width;
        rdcEmpty1.Name = "f_empty_temp_empty_column_Footer";
        //rdcEmpty.Value = "   ";
        rdcEmpty1.writeElement(writer, styl);*/
        writer.WriteEndElement();
        writer.WriteEndElement();
        //




        string fieldName = "";
        for (int iFieldCount = 0; iFieldCount < m_fields.Count; iFieldCount++)
        {
            fieldName = m_fields[iFieldCount].ToString();
            writer.WriteStartElement("TableCell");
            writer.WriteStartElement("ReportItems");
            // Textbox
            RDLCTextBox rdcField = new RDLCTextBox();
            string alignment = getFieldAlignment(dsReportInput, fieldName); // srivatsan for header alignment
            if (hsStyle != null)
            {
                if (hsStyle.Contains("TextAlign"))
                {
                    hsStyle["TextAlign"] = alignment;
                }
                if (hsStyle.Contains("FontWeight"))
                    hsStyle["FontWeight"] = "800";
                else
                    hsStyle.Add("FontWeight", "800");
            }

            rdcField.CanGrow = true;
            //rdcField.CanShrink = true;
            rdcField.CanShrink = false;
            rdcField.Top = dTop;
            rdcField.Left = dLeft;
            rdcField.Height = 0.2;
            //string sFieldName = getFieldName(dsReportInput, fieldName);
            string fieldType = "";
            if (fieldName != "")
            {
                rdcField.Name = "f_" + fieldName + "_Footer";
                //if (sFieldName.Equals(strGTotalField))
                if (strGTotalField.Contains(fieldName))
                {
                    fieldType = getFieldType(dsReportInput, fieldName);

                    #region Old Code commented by 'Imran Gani' on 28-Feb-2014, for locale support.
                    //if (fieldType.ToUpper() == "CU")
                    //{
                    //    if (hsStyle.Contains("Language"))
                    //        hsStyle["Language"] = ll.getUserCulture().ToString();
                    //    else
                    //        hsStyle.Add("Language", ll.getUserCulture().ToString());

                    //    if (hsStyle.Contains("Format"))
                    //        hsStyle["Format"] = ll.getUserCurrencyCode() + " #,#.00";
                    //    else
                    //        hsStyle.Add("Format", ll.getUserCurrencyCode() + " #,#.00");
                    //}
                    //else if (fieldType.ToUpper() == "DC")
                    //{
                    //    if (hsStyle.Contains("Format"))
                    //        hsStyle["Format"] = "#,##0.00";
                    //    else
                    //        hsStyle.Add("Format", "#,##0.00");
                    //}
                    ////    rdcField.Value = "=FormatCurrency(Sum(Fields!" + fieldName + ".Value))";
                    ////else if (fieldType.ToUpper() == "DC")
                    ////    rdcField.Value = "=FormatNumber(Sum(Fields!" + fieldName + ".Value),2)";
                    ////else
                    #endregion

                    #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                    string sLocale = HttpContext.Current.Session["userlocale"].ToString();
                    switch (fieldType.ToUpper())
                    {
                        case "CU":
                            if (hsStyle.Contains("Language"))
                                hsStyle["Language"] = MBLocalization.getCultureInfo(sLocale).ToString();
                            else
                                hsStyle.Add("Language", MBLocalization.getCultureInfo(sLocale).ToString());

                            if (hsStyle.Contains("Format"))
                                hsStyle["Format"] = MBLocalization.getCurrencyCode(sLocale) + " #,#.00";
                            else
                                hsStyle.Add("Format", MBLocalization.getCurrencyCode(sLocale) + " #,#.00");
                            break;
                        case "NU":
                        case "AN":
                            if (hsStyle.Contains("Language"))
                                hsStyle["Language"] = MBLocalization.getCultureInfo(sLocale).ToString();
                            else
                                hsStyle.Add("Language", MBLocalization.getCultureInfo(sLocale).ToString());

                            if (hsStyle.Contains("Format"))
                                hsStyle["Format"] = " #,#";
                            else
                                hsStyle.Add("Format", " #,#");
                            break;
                        case "DC":
                        case "FL":
                            if (hsStyle.Contains("Language"))
                                hsStyle["Language"] = MBLocalization.getCultureInfo(sLocale).ToString();
                            else
                                hsStyle.Add("Language", MBLocalization.getCultureInfo(sLocale).ToString());

                            if (hsStyle.Contains("Format"))
                                hsStyle["Format"] = " #,#.00";
                            else
                                hsStyle.Add("Format", " #,#.00");
                            break;
                    }
                    #endregion
                    rdcField.Value = "=Sum(Fields!" + fieldName + ".Value)"; //sFieldName;---------------------
                }
                else
                    rdcField.Value = ""; //sFieldName;---------------------
                rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
                dLeft = dLeft + rdcField.Width;
            }
            else
            {
                rdcField.Name = "th_" + fieldName + "_Footer";
                //if (fieldName.Equals(strGTotalField))
                if (strGTotalField.Contains(fieldName))
                {
                    #region Old Code commented by 'Imran Gani' on 28-Feb-2014, for locale support.
                    //if (fieldType.ToUpper() == "CU")
                    //{
                    //    if (hsStyle.Contains("Language"))
                    //        hsStyle["Language"] = ll.getUserCulture().ToString();
                    //    else
                    //        hsStyle.Add("Language", ll.getUserCulture().ToString());

                    //    if (hsStyle.Contains("Format"))
                    //        hsStyle["Format"] = ll.getUserCurrencyCode() + " #,#.00";
                    //    else
                    //        hsStyle.Add("Format", ll.getUserCurrencyCode() + " #,#.00");
                    //}
                    //else if (fieldType.ToUpper() == "DC")
                    //{
                    //    if (hsStyle.Contains("Format"))
                    //        hsStyle["Format"] = "#,##0.00";
                    //    else
                    //        hsStyle.Add("Format", "#,##0.00");
                    //}
                    ////fieldType = getFieldType(dsReportInput, fieldName);
                    ////if (fieldType.ToUpper() == "CU")
                    ////    rdcField.Value = "=FormatCurrency(Sum(Fields![" + fieldName + "].Value))";
                    ////else if (fieldType.ToUpper() == "DC")
                    ////    rdcField.Value = "=FormatNumber(Sum(Fields![" + fieldName + "].Value),2)";
                    ////else
                    #endregion

                    #region New code Added by 'Imran Gani' on 28-Feb-2014, to use switch case with MBLocale
                    string sLocale = HttpContext.Current.Session["userlocale"].ToString();
                    switch (fieldType.ToUpper())
                    {
                        case "CU":
                            if (hsStyle.Contains("Language"))
                                hsStyle["Language"] = MBLocalization.getCultureInfo(sLocale).ToString();
                            else
                                hsStyle.Add("Language", MBLocalization.getCultureInfo(sLocale).ToString());

                            if (hsStyle.Contains("Format"))
                                hsStyle["Format"] = MBLocalization.getCurrencyCode(sLocale) + " #,#.00";
                            else
                                hsStyle.Add("Format", MBLocalization.getCurrencyCode(sLocale) + " #,#.00");
                            break;
                        case "NU":
                        case "AN":
                            if (hsStyle.Contains("Language"))
                                hsStyle["Language"] = MBLocalization.getCultureInfo(sLocale).ToString();
                            else
                                hsStyle.Add("Language", MBLocalization.getCultureInfo(sLocale).ToString());

                            if (hsStyle.Contains("Format"))
                                hsStyle["Format"] = " #,#";
                            else
                                hsStyle.Add("Format", " #,#");
                            break;
                        case "DC":
                        case "FL":
                            if (hsStyle.Contains("Language"))
                                hsStyle["Language"] = MBLocalization.getCultureInfo(sLocale).ToString();
                            else
                                hsStyle.Add("Language", MBLocalization.getCultureInfo(sLocale).ToString());

                            if (hsStyle.Contains("Format"))
                                hsStyle["Format"] = " #,#.00";
                            else
                                hsStyle.Add("Format", " #,#.00");
                            break;
                    }
                    #endregion
                    rdcField.Value = "=Sum(Fields!" + fieldName + ".Value)";
                    //rdcField.Value = "=Sum(Fields!" + fieldName + ".Value)";  //fieldName;---------------------
                }
                else
                    rdcField.Value = "";
                rdcField.Width = Convert.ToDouble(m_FieldLength[iFieldCount].ToString().Replace("in", ""));// *0.1;
                dLeft = dLeft + rdcField.Width;
            }
            rdcField.Style = hsStyle;

            rdcField.writeElement(writer, styl);
            writer.WriteEndElement();
            writer.WriteEndElement();
            if (iFieldCount != m_fields.Count - 1)
            {
                writer.WriteStartElement("TableCell");
                writer.WriteStartElement("ReportItems");
                RDLCTextBox rdcEmpty = new RDLCTextBox();
                rdcEmpty.CanGrow = true;
                rdcEmpty.CanShrink = true;
                rdcEmpty.Top = dTop;
                rdcEmpty.Left = dLeft;
                rdcEmpty.Height = 0.2;
                rdcEmpty.Width = 0.15;
                rdcEmpty.Style = hsStyle;
                dLeft = dLeft + rdcEmpty.Width;
                rdcEmpty.Name = "f_empty_" + fieldName + "_Footer";
                //rdcEmpty.Value = "   ";
                rdcEmpty.writeElement(writer, styl);
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
        }

        writer.WriteEndElement(); // TableCells
        writer.WriteElementString("Height", "0.25in");
        writer.WriteEndElement(); // TableRow
        writer.WriteEndElement(); // TableRows
        writer.WriteElementString("RepeatOnNewPage", "true");
        writer.WriteEndElement(); // Footer
    }

    private void writeGrouping(DataSet dsReportInput)
    {
        if (dsReportInput.Tables["p_report_grouping"] == null) return;
        if (dsReportInput.Tables["p_report_grouping"].Rows.Count == 0) return;

        writer.WriteStartElement("TableGroups");//<TableGroups>

        int groupCount = 1;
        string groupingfield = "";// headerField = "";//subTotalField="";
        ArrayList subTotalField = new ArrayList();
        ArrayList headerField = new ArrayList();
        foreach (DataRow drGroup in dsReportInput.Tables["p_report_grouping"].Rows)
        {
            #region grouping header
            if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToUpper().Equals("SQL"))
            {
                groupingfield = drGroup["grouping_field"].ToString();
                DataRow[] drArr = dsReportInput.Tables["p_report_grouping_header"].Select("rpt_group_id='" + drGroup["af_row_id"].ToString() + "'");
                if (drArr.Length > 0)
                {
                    foreach (DataRow drHeader in drArr)
                        headerField.Add(drHeader["header_field"].ToString());
                }
                else
                    headerField = new ArrayList();
            }
            else
            {
                groupingfield = getColumnName(drGroup["grouping_field"].ToString());
                DataRow[] drArr = dsReportInput.Tables["p_report_grouping_header"].Select("rpt_group_id='" + drGroup["af_row_id"].ToString() + "'");
                if (drArr.Length > 0)
                {
                    foreach (DataRow drHeader in drArr)
                        headerField.Add(getColumnName(drHeader["header_field"].ToString()));
                }
                else
                    headerField = new ArrayList();
            }

            writer.WriteStartElement("TableGroup");//<TableGroup>
            writer.WriteStartElement("Grouping");//<Grouping Name="table1_Group1">
            writer.WriteAttributeString("Name", null, "table1_Group" + groupCount.ToString());

            writer.WriteStartElement("GroupExpressions");//<GroupExpressions>
            writer.WriteElementString("GroupExpression", "=Fields!" + groupingfield + ".Value");//<GroupExpression>=Fields!parent_menu_id.Value</GroupExpression>

            writer.WriteEndElement();//</GroupExpressions>
            writer.WriteEndElement();//</Grouping>

            writer.WriteStartElement("Header");//<Header>
            writer.WriteStartElement("TableRows");//<TableRows>
            writer.WriteStartElement("TableRow");//<TableRow>            
            writer.WriteStartElement("TableCells");//<TableCells>

            if (headerField.Count > 0)
            {
                writer.WriteStartElement("TableCell");//<TableCell>
                writer.WriteElementString("ColSpan", (dsReportInput.Tables["p_sy_report_att"].Rows.Count * 2).ToString());
                writer.WriteStartElement("ReportItems");//<ReportItems>
                writer.WriteStartElement("Textbox");//<Textbox Name="textbox4">
                writer.WriteAttributeString("Name", null, "textboxg" + groupCount.ToString() + "c1");
                writer.WriteElementString("rd:DefaultName", "textboxg" + groupCount.ToString() + "c1");//<rd:DefaultName>textbox4</rd:DefaultName>
                writer.WriteStartElement("Style");//<Style>
                writer.WriteElementString("PaddingLeft", "2pt");//<PaddingLeft>2pt</PaddingLeft>
                writer.WriteElementString("PaddingRight", "2pt");//<PaddingRight>2pt</PaddingRight>
                writer.WriteElementString("PaddingTop", "2pt");//<PaddingTop>2pt</PaddingTop>
                writer.WriteElementString("PaddingBottom", "2pt");//<PaddingBottom>2pt</PaddingBottom>
                writer.WriteElementString("VerticalAlign", "Middle");
                writer.WriteElementString("FontSize", "8.5pt");
                writer.WriteElementString("FontWeight", "Bold");
                writer.WriteEndElement();//</Style>
                writer.WriteElementString("ZIndex", "23");//<ZIndex>23</ZIndex>
                writer.WriteElementString("CanGrow", "true");//                  <CanGrow>true</CanGrow>
                writer.WriteElementString("CanShrink", "false");//                  

                string headerTxt = "";
                foreach (object obj in headerField)
                {
                    string fieldType = getFieldType(dsReportInput, obj.ToString());
                    if (fieldType.ToUpper() == "CU")
                        headerTxt += "\"" + obj.ToString() + " : \"& Space(20) & FormatCurrency(CDEC(Fields!" + obj.ToString() + ".Value)) & Space(50) &";
                    else if (fieldType.ToUpper() == "DC")
                        headerTxt += "\"" + obj.ToString() + " : \"& Space(20) & FormatNumber(CDEC(Fields!" + obj.ToString() + ".Value)) & Space(50) &";
                    else
                        headerTxt += "\"" + obj.ToString() + " : \"& Space(20) & Fields!" + obj.ToString() + ".Value & Space(50) &";

                    //rdlctxtbox.Value = "=\"Page \" & Globals!PageNumber & \" of \" & Globals!TotalPages";
                    // "=\"Incentive : \"& Fields!incentive_name.Value"

                }
                headerTxt = "=" + headerTxt.Remove(headerTxt.LastIndexOf('&'));
                //writer.WriteElementString("Value", "=Fields!" + headerTxt + ".Value");//                  <Value>=Fields!parent_menu_id.Value</Value>
                writer.WriteElementString("Value", headerTxt);//                  <Value>=Fields!parent_menu_id.Value</Value>                    

                writer.WriteEndElement();//</Textbox>
                writer.WriteEndElement();//</ReportItems>
                writer.WriteEndElement();//</TableCell>
            }
            else
            {
                for (int i = 1; i <= dsReportInput.Tables["p_sy_report_att"].Rows.Count * 2; i++)
                {
                    writer.WriteStartElement("TableCell");//<TableCell>
                    writer.WriteStartElement("ReportItems");//<ReportItems>
                    writer.WriteStartElement("Textbox");//<Textbox Name="textbox4">
                    writer.WriteAttributeString("Name", null, "textboxg" + groupCount.ToString() + "c" + i.ToString());
                    writer.WriteElementString("rd:DefaultName", "textboxg" + groupCount.ToString() + "c" + i.ToString());//<rd:DefaultName>textbox4</rd:DefaultName>
                    writer.WriteStartElement("Style");//<Style>
                    writer.WriteElementString("PaddingLeft", "2pt");//<PaddingLeft>2pt</PaddingLeft>
                    writer.WriteElementString("PaddingRight", "2pt");//<PaddingRight>2pt</PaddingRight>
                    writer.WriteElementString("PaddingTop", "2pt");//<PaddingTop>2pt</PaddingTop>
                    writer.WriteElementString("PaddingBottom", "2pt");//<PaddingBottom>2pt</PaddingBottom>
                    writer.WriteEndElement();//</Style>
                    writer.WriteElementString("ZIndex", "23");//<ZIndex>23</ZIndex>
                    writer.WriteElementString("CanGrow", "true");//                  <CanGrow>true</CanGrow>
                    writer.WriteElementString("CanShrink", "false");//                  

                    //if ((i == 1) && (headerField.Count > 0))
                    //{
                    //    string headerTxt = "=(";
                    //    foreach (object obj in headerField)
                    //    {
                    //        //rdlctxtbox.Value = "=\"Page \" & Globals!PageNumber & \" of \" & Globals!TotalPages";
                    //        headerTxt += "\" " + obj.ToString() + " : " + "\" & (Fields!" + obj.ToString() + ".Value)+";
                    //    }
                    //    headerTxt = headerTxt.Remove(headerTxt.LastIndexOf('+')) + ")";
                    //    //writer.WriteElementString("Value", "=Fields!" + headerTxt + ".Value");//                  <Value>=Fields!parent_menu_id.Value</Value>
                    //    writer.WriteElementString("Value", headerTxt);//                  <Value>=Fields!parent_menu_id.Value</Value>                    
                    //}
                    //else
                    writer.WriteElementString("Value", "");//                  <Value>=Fields!parent_menu_id.Value</Value>

                    writer.WriteEndElement();//</Textbox>
                    writer.WriteEndElement();//</ReportItems>
                    writer.WriteEndElement();//</TableCell>
                }
            }
            writer.WriteEndElement();//</TableCells>
            writer.WriteElementString("Height", "0.10in");//   "0.25in"       <Height>0.25in</Height>
            writer.WriteEndElement();//</TableRow>
            writer.WriteEndElement();//</TableRows>

            writer.WriteElementString("RepeatOnNewPage", "true");//      <RepeatOnNewPage>true</RepeatOnNewPage>

            writer.WriteEndElement();//    </Header>
            #endregion

            #region grouping subtotal
            writer.WriteStartElement("Footer");//    <Footer>
            writer.WriteStartElement("TableRows");//      <TableRows>
            writer.WriteStartElement("TableRow");//        <TableRow>
            writer.WriteStartElement("TableCells");//          <TableCells>

            Hashtable hsLoc = new Hashtable();
            if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
            {
                DataRow[] drrArr = dsReportInput.Tables["p_report_grouping_subtotal"].Select("rpt_group_id='" + drGroup["af_row_id"].ToString() + "'");
                if (drrArr.Length > 0)
                {
                    foreach (DataRow drSubTotal in drrArr)
                    {
                        DataRow[] drF = dsReportInput.Tables["p_sy_report_att"].Select("temp_attrib_id = '" + drSubTotal["subtotal_field"].ToString() + "'");
                        if (drF.Length > 0)
                        {
                            subTotalField.Add(drF[0]["attrib_id"].ToString());
                        }
                        drF = null;
                    }
                }
                drrArr = null;
            }
            else
            {
                DataRow[] drrArr = dsReportInput.Tables["p_report_grouping_subtotal"].Select("rpt_group_id='" + drGroup["af_row_id"].ToString() + "'");
                if (drrArr.Length > 0)
                {
                    foreach (DataRow drSubTotal in drrArr)
                    {
                        subTotalField.Add(drSubTotal["subtotal_field"].ToString());
                    }
                }
                drrArr = null;
            }

            for (int i = 0; i < dsReportInput.Tables["p_sy_report_att"].Rows.Count; i++)
            {
                DataRow drF = dsReportInput.Tables["p_sy_report_att"].Rows[i];
                if (subTotalField.Contains(drF["attrib_id"]))
                    hsLoc.Add(drF["attrib_id"], (i + 1) * 2);
                drF = null;
            }

            for (int i = 1; i <= dsReportInput.Tables["p_sy_report_att"].Rows.Count * 2; i++)
            {
                //subTotalField = new ArrayList();
                //int columnIndex;
                ////if (i % 2 == 0)
                //if (i % 2 > 0)
                //    columnIndex = i / 2;
                //else
                //    columnIndex = -1;

                //DataRow[] drrArr = dsReportInput.Tables["p_report_grouping_subtotal"].Select("rpt_group_id='" + drGroup["af_row_id"].ToString() + "'");
                //if (drrArr.Length > 0)
                //{
                //    foreach (DataRow drSubTotal in drrArr)
                //    {
                //        subTotalField.Add(drSubTotal["subtotal_field"].ToString());
                //    }
                //}
                //subTotalField = drrArr[0]["subtotal_field"].ToString();
                writer.WriteStartElement("TableCell");//            <TableCell>
                writer.WriteStartElement("ReportItems");//              <ReportItems>
                writer.WriteStartElement("Textbox");//                <Textbox Name="textbox13">
                writer.WriteAttributeString("Name", null, "textboxgf" + groupCount.ToString() + "c" + i.ToString());
                writer.WriteElementString("rd:DefaultName", "textboxgf" + groupCount.ToString() + "c" + i.ToString());//                  <rd:DefaultName>textbox13</rd:DefaultName>
                writer.WriteStartElement("Style");//                  <Style>
                //writer.WriteElementString("PaddingLeft", "2pt");//                    <PaddingLeft>2pt</PaddingLeft>
                //writer.WriteElementString("PaddingRight", "2pt");//                    <PaddingRight>2pt</PaddingRight>
                //writer.WriteElementString("PaddingTop", "2pt");//                    <PaddingTop>2pt</PaddingTop>
                //writer.WriteElementString("PaddingBottom", "2pt");//                    <PaddingBottom>2pt</PaddingBottom>                 
                writer.WriteElementString("TextAlign", "Right");
                writer.WriteElementString("FontSize", "8pt");
                writer.WriteElementString("FontWeight", "800");
                writer.WriteElementString("VerticalAlign", "Middle");
                writer.WriteEndElement();//</Style>
                writer.WriteElementString("ZIndex", "11");//                  <ZIndex>11</ZIndex>
                writer.WriteElementString("CanGrow", "true");//                  <CanGrow>true</CanGrow>

                if (subTotalField.Count > 0)
                {
                    //if ((dsReportInput.Tables["p_sy_report_att"].Rows.Count > columnIndex) && (columnIndex > -1))
                    //{
                    string strSubTotalField = "";
                    foreach (object obj in subTotalField)
                    {
                        if (Convert.ToInt32(hsLoc[obj].ToString()) == i)
                        {
                            strSubTotalField = obj.ToString();
                            break;
                            //if (dsReportInput.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
                            //{
                            //    if (dsReportInput.Tables["p_sy_report_att"].Rows[columnIndex]["attrib_id"].Equals(obj.ToString()))
                            //    {
                            //        strSubTotalField = obj.ToString();
                            //        break;
                            //    }
                            //}
                            //else if (dsReportInput.Tables["p_sy_report_att"].Rows[columnIndex]["attrib_id"].Equals(getColumnName(obj.ToString())))
                            //{
                            //    strSubTotalField = getColumnName(obj.ToString());
                            //    break;
                            //}
                        }
                    }
                    if (strSubTotalField != "")
                    {
                        string fieldType = getFieldType(dsReportInput, strSubTotalField);
                        if (fieldType.ToUpper() == "CU")
                            writer.WriteElementString("Value", "=FormatCurrency(Sum(Fields!" + strSubTotalField + ".Value))");
                        else if (fieldType.ToUpper() == "DC")
                            writer.WriteElementString("Value", "=FormatNumber(Sum(Fields!" + strSubTotalField + ".Value),2)");
                        else
                            writer.WriteElementString("Value", "=Sum(Fields!" + strSubTotalField + ".Value)");//                  <Value />
                    }
                    else
                        writer.WriteElementString("Value", "");//                  <Value />
                    //}
                    //else
                    //    writer.WriteElementString("Value", "");//                  <Value />
                }
                else
                    writer.WriteElementString("Value", "");//                  <Value />

                writer.WriteEndElement();//</Textbox>
                writer.WriteEndElement();//</ReportItems>
                writer.WriteEndElement();//</TableCell>
            }

            writer.WriteEndElement();//</TableCells>
            writer.WriteElementString("Height", "0.10in");//          <Height>0.25in</Height>
            writer.WriteEndElement();//</TableRow>
            writer.WriteEndElement();//</TableRows>
            writer.WriteEndElement();//</Footer>
            writer.WriteEndElement();//</TableGroup>
            #endregion

            groupCount++;
        }
        writer.WriteEndElement();//</TableGroups>
    }

    private string getColumnName(string afRowID)
    {
        string sql = "select attrib_id from sy_obj_att where af_row_id='" + afRowID + "'";
        HDDatabase HDD = new HDDatabase();
        return Convert.ToString(HDD.GetColumnValue(sql));
    }

    public void writeMatrixRow(String name, String value)
    {
        writer.WriteStartElement("MatrixRows");
        writer.WriteStartElement("MatrixRow");
        writer.WriteElementString("Height", "0.5in");
        writer.WriteStartElement("MatrixCells");
        writer.WriteStartElement("MatrixCell");
        writer.WriteStartElement("ReportItems");
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", name);
        writer.WriteElementString("rd:DefaultName", name);

        styl.init("RowGrouping");
        styl.writeRDLCStyle(writer);

        /*writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingLeft", "2pt");
        writer.WriteElementString("PaddingBottom", "2pt");
        writer.WriteElementString("PaddingRight", "2pt");
        writer.WriteElementString("PaddingTop", "2pt");
        writer.WriteEndElement(); //Style*/

        writer.WriteElementString("CanGrow", "true");
        writer.WriteElementString("Value", value);
        writer.WriteEndElement(); //Textbox
        writer.WriteEndElement(); //ReportItems
        writer.WriteEndElement();//MatrixCell
        writer.WriteEndElement();//MatrixCells
        writer.WriteEndElement();//MatrixRow
        writer.WriteEndElement();//MatrixRows
    }

    public void writeCorner(String name, String value, int zindex)
    {
        writer.WriteStartElement("Corner");
        writer.WriteStartElement("ReportItems");
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", name);
        writer.WriteElementString("rd:DefaultName", name);
        writer.WriteElementString("ZIndex", "" + zindex);

        /*writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingLeft", "2pt");
        writer.WriteElementString("PaddingBottom", "2pt");
        writer.WriteElementString("PaddingRight", "2pt");
        writer.WriteElementString("PaddingTop", "2pt");
        writer.WriteEndElement(); //Style*/
        styl.writeRDLCStyle(writer);

        writer.WriteElementString("CanGrow", "true");
        writer.WriteElementString("Value", value);
        writer.WriteEndElement(); //Textbox
        writer.WriteEndElement(); //ReportItems
        writer.WriteEndElement();//Corner
    }

    public void writeCoumnGroupings()
    {
        writer.WriteStartElement("ColumnGroupings");
        writer.WriteStartElement("ColumnGrouping");
        writer.WriteStartElement("DynamicColumns");
        writer.WriteStartElement("ReportItems");
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", "textbox2");
        writer.WriteElementString("rd:DefaultName", "textbox2");
        writer.WriteElementString("ZIndex", "2");

        /*writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingLeft", "2pt");
        writer.WriteElementString("PaddingBottom", "2pt");
        writer.WriteElementString("PaddingRight", "2pt");
        writer.WriteElementString("PaddingTop", "2pt");
        writer.WriteEndElement(); //Style*/
        styl.writeRDLCStyle(writer);

        writer.WriteElementString("CanGrow", "true");
        writer.WriteElementString("Value", "=Fields!" + columnGroupingField + ".Value");
        writer.WriteEndElement(); //Textbox
        writer.WriteEndElement(); //ReportItems

        writer.WriteStartElement("Grouping");
        writer.WriteAttributeString("Name", "matrix1_ColumnGroup1");
        writer.WriteStartElement("GroupExpressions");
        writer.WriteElementString("GroupExpression", "=Fields!" + columnGroupingField + ".Value");
        //writer.WriteEndElement();//GroupExpression
        writer.WriteEndElement();//GroupExpressions
        writer.WriteEndElement();//Grouping
        writer.WriteEndElement();//DynamicColumns

        writer.WriteElementString("Height", "0.5in");
        writer.WriteEndElement();//ColumnGrouping
        writer.WriteEndElement();//ColumnGroupings
    }

    public void writeRowGroupings()
    {
        writer.WriteStartElement("RowGroupings");
        writer.WriteStartElement("RowGrouping");
        writer.WriteElementString("Width", "2.1875in");

        writer.WriteStartElement("DynamicRows");
        writer.WriteStartElement("ReportItems");
        writer.WriteStartElement("Textbox");
        writer.WriteAttributeString("Name", "textbox3");
        writer.WriteElementString("rd:DefaultName", "textbox3");
        writer.WriteElementString("ZIndex", "1");

        /*writer.WriteStartElement("Style");
        writer.WriteElementString("PaddingLeft", "2pt");
        writer.WriteElementString("PaddingBottom", "2pt");
        writer.WriteElementString("PaddingRight", "2pt");
        writer.WriteElementString("PaddingTop", "2pt");
        writer.WriteEndElement(); //Style*/
        styl.writeRDLCStyle(writer);

        writer.WriteElementString("CanGrow", "true");
        writer.WriteElementString("Value", "=Fields!" + rowGroupingField + ".Value");
        writer.WriteEndElement(); //Textbox
        writer.WriteEndElement(); //ReportItems
        writeGrouping("matrix1_RowGroup1", rowGroupingField);
        /*   writer.WriteStartElement("Grouping");
           writer.WriteAttributeString("Name", "matrix1_RowGroup1");
           writer.WriteStartElement("GroupExpressions");
           writer.WriteElementString("GroupExpression", "=Fields!" + rowGroupingField + ".Value");

           writer.WriteEndElement();//GroupExpressions
           writer.WriteEndElement();//Grouping*/
        writer.WriteEndElement();//DynamicRows
        writer.WriteEndElement();//RowGrouping
        writer.WriteEndElement();//RowGroupings



    }

    private string getLogo()
    {
        string logopath = "";
        try
        {
            if (HttpContext.Current.Session["company_afrowid"] != null)
            {
                DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(".") + "\\Images\\CustomLogo");
                FileInfo[] fis = di.GetFiles(HttpContext.Current.Session["company_afrowid"].ToString() + "*");
                if (fis.Length > 0)
                {
                    logopath = "images/CustomLogo/" + fis[0].Name + "";
                }
                else//if another user in the same company logs out
                {
                    if (HttpContext.Current.Session["hasCustomLogo"] != null)
                    {
                        if (HttpContext.Current.Session["hasCustomLogo"].ToString() == "1")
                        {
                            string fName = ""; string ext = "";
                            security s = new security();
                            s.createCustomLogo(ref fName, ref ext);
                            logopath = "images/CustomLogo/" + HttpContext.Current.Session["company_afrowid"] + ext;
                        }
                        //ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td style=background:url('images/CustomLogo/" + Session["company_afrowid"] + ext + "');></td></tr></table>";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getLogo: Error: " + ex.Message);
        }
        return logopath;
    }

}

public class MatrixRDLC : MyRDLC
{
    public MatrixRDLC()
    {

    }

    public void GenerateMatrixRdlc(String absFilePath)
    {
        writeInitRDLC(absFilePath);
        writeDataSource("DataSource1");

        writer.WriteElementString("BottomMargin", "1in");
        writer.WriteElementString("RightMargin", "1in");

        writer.WriteElementString("rd:DrawGrid", "true");
        writer.WriteElementString("InteractiveWidth", "8.5in");
        writer.WriteElementString("rd:SnapToGrid", "true");

        // Body element
        writer.WriteStartElement("Body");
        //writer.WriteElementString("Height", "5in");

        // ReportItems element
        writer.WriteStartElement("ReportItems");

        // Table element
        writer.WriteStartElement("Matrix");
        writer.WriteAttributeString("Name", null, "matrix1");
        writer.WriteStartElement("MatrixColumns");
        writer.WriteStartElement("MatrixColumn");
        writer.WriteElementString("Width", "2.1875in");
        writer.WriteEndElement();//MatrixColumn
        writer.WriteEndElement();//MatrixColumns

        writer.WriteElementString("Left", "0.5in");

        writeRowGroupings();

        writeCoumnGroupings();

        writer.WriteElementString("Top", "0.375in");
        writer.WriteElementString("Width", "4.375in");

        writeCorner("textbox1", "", 3);

        writer.WriteElementString("Height", "1in");

        //writeMatrixRow();
        writeMatrixRow("textbox4", "=Fields!attrib_id.Value");


        writer.WriteEndElement();//Matrix
        writer.WriteEndElement();//ReportItems

        writer.WriteElementString("Height", "1in");

        writer.WriteEndElement();//Body

        writer.WriteElementString("rd:ReportID", m_reportid);

        writeDataset(null);

        writer.WriteElementString("LeftMargin", "1in");

        /*// DataSet element
        writer.WriteStartElement("DataSets");
        writer.WriteStartElement("DataSet");
        writer.WriteAttributeString("Name", null, "DataSet1");

        // Query element
        writer.WriteStartElement("Query");
        writer.WriteElementString("DataSourceName", "DataSource1");
        //writer.WriteElementString("CommandType", "Text");
        writer.WriteElementString("CommandText", m_commandText);
        writer.WriteElementString("Timeout", "30");
        writer.WriteEndElement(); // Query*/

        writer.WriteElementString("Width", "6.5in");
        writer.WriteElementString("InteractiveHeight", "11in");
        writer.WriteElementString("Language", "en-US");
        writer.WriteElementString("TopMargin", "1in");

        /*   writer.WriteEndElement();//Report

           // Flush the writer and close the stream
           writer.Flush();
           stream.Close();*/
        //writeEndRDLC();
    }

    public void buildMatrixRDLC(String absFilePath)
    {
        try
        {
            // Call methods to create the RDL
            this.OpenConnection();
            //this.GenerateFieldsList();
            this.GenerateMatrixRdlc(absFilePath);

            //Console.WriteLine("RDL file generated successfully.");
        }

        catch (Exception exception)
        {
            //Console.WriteLine("An error occurred: " + exception.Message);
        }

        finally
        {
            // Close the connection string
            m_connection.Close();
        }
    }
}

public class getDataFromSQLandFormat
{
    DataSet dsTables = new DataSet();
    string sSQL = "";
    ArrayList currencyCode_Rate = new ArrayList();

    public getDataFromSQLandFormat(string SQL)
    {
        sSQL = SQL;
    }

    public getDataFromSQLandFormat()
    {
    }

    public DataTable getData(ref DataSet dsInputInfo)
    {
        DataTable dtData = new DataTable();
        try
        {
            //SqlDataAdapter objAdapter = null;
            //SqlConnection sqlConn = null;
            //SqlCommand command = null;
            //sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            //sqlConn.Open();
            //command = sqlConn.CreateCommand();
            //command.CommandText = sSQL;
            //objAdapter = new SqlDataAdapter(command);
            //objAdapter.Fill(dtData);
            //sqlConn.Close();

            //if (dtData.Rows.Count > 0 && dtData.Columns.Contains("created_by"))
            //{
            //    SecurityFilter SF = new SecurityFilter();
            //    DataSet dseObj = SF.GetFilterDataset(sSQL);
            //    dtData = dseObj.Tables[0].Copy();
            //    dseObj.Dispose();
            //    dseObj = null;
            //}
            HDDatabase HDD = new HDDatabase();
            dtData = HDD.GetDataTable(sSQL, false);
            ProcessDataTable(ref dtData, ref dsInputInfo);
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("getData : Error : " + Ex.Message);
        }
        return dtData;
    }

    private void addFieldLengthColumn(ref DataSet dsReportInfo)
    {
        try
        {
            if (dsReportInfo.Tables["p_sy_report_att"].Columns.Contains("mb_field_length")) return;
            DataColumn dc = new DataColumn("mb_field_length");
            dsReportInfo.Tables["p_sy_report_att"].Columns.Add(dc);
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("addFieldLengthColumn : Error : " + Ex.Message);
        }
    }

    // Added by srivatsan for setting the DataType of column in DAtaColumn extended properties
    private void SetDataTypeofColumn(ref DataColumn dc, string strDataType)
    {
        try
        {

            if (strDataType.Trim() != "")
            {
                dc.ExtendedProperties.Add("DataType", strDataType.Trim().ToUpper());
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SetDataTypeofColumn :" + ex.Message);
        }
        finally
        {

        }
    }

    private bool ProcessDataTable(ref DataTable dtData, ref DataSet dsPageInfo)
    {
        try
        {
            dsTables = getAttribDataType(ref dtData, ref dsPageInfo);
            addFieldLengthColumn(ref dsPageInfo);

            DataTable dtTemp = dtData.Copy();
            DynamicDisplayI DDI = new DynamicDisplayI();
            string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            DDI = null;

            //modified by Sampath for new report designer
            if (dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString() == "" || dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "false" || dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
            {
                parseForMasterDetail(ref dtData, ref dsPageInfo, ref dsTables);
                parseForBindFields(ref dtData, ref dsPageInfo, ref dsTables);
                dtTemp = dtData.Copy();
                foreach (DataColumn dc in dtData.Columns)
                {
                    DataRow[] drReportAttrib = null;
                    if (dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
                        drReportAttrib = dsPageInfo.Tables["p_sy_report_att"].Select("attrib_name='" + dc.ColumnName.Replace("'", "''") + "'");
                    else
                        drReportAttrib = dsPageInfo.Tables["p_sy_report_att"].Select("attrib_id='" + dc.ColumnName.Replace("'", "''") + "'");

                    if (drReportAttrib.Length > 0)
                    {
                        DataRow[] drObjAttrib = null;

                        if (dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
                            drObjAttrib = dsTables.Tables[drReportAttrib[0]["object_id"].ToString() + "_att"].Select("af_row_id='" + drReportAttrib[0]["attrib_id"].ToString().Replace("'", "''") + "'"); // Modified by 'Imran Gani' on 28-Aug-12, for selecting the record based on af_row_id rather then attrib_id.
                        else
                            drObjAttrib = dsTables.Tables[drReportAttrib[0]["object_id"].ToString() + "_att"].Select("attrib_id='" + drReportAttrib[0]["attrib_id"].ToString().Replace("'", "''") + "'");
                        if (drObjAttrib.Length > 0)
                        {
                            dtTemp = parseForDataType(dc, ref dtTemp, ref  drObjAttrib[0], ref drReportAttrib[0], sUTC_Offset);

                            string sDataType = drObjAttrib[0]["attrib_data_type"].ToString();
                            DataColumn dctemp = dtTemp.Columns[dc.ColumnName];
                            //SetDataTypeofColumn(ref dtTemp.Columns[dc.ColumnName], sDataType);
                            SetDataTypeofColumn(ref dctemp, sDataType);

                        }
                        else
                        {
                            int iFieldLength = 0;
                            foreach (DataRow dr in dtTemp.Rows)
                            {
                                if (dr[dc.ColumnName] != System.DBNull.Value)
                                {
                                    if (iFieldLength < dr[dc.ColumnName].ToString().Length)
                                        iFieldLength = dr[dc.ColumnName].ToString().Length;
                                }
                            }
                            if (iFieldLength < drReportAttrib[0]["caption"].ToString().Length)
                                iFieldLength = drReportAttrib[0]["caption"].ToString().Length;

                            if (iFieldLength > 15)
                                drReportAttrib[0]["mb_field_length"] = iFieldLength * 0.08;// +"in";
                            else
                            {
                                if (iFieldLength < 6) iFieldLength = 5;
                                drReportAttrib[0]["mb_field_length"] = iFieldLength * 0.1;// +"in";
                            }
                        }
                    }
                }
            }
            else if (dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "true" || dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "sql")
            {
                foreach (DataColumn dc in dtData.Columns)
                {
                    DataRow[] drReportAttrib = dsPageInfo.Tables["p_sy_report_att"].Select("attrib_id='" + dc.ColumnName.Replace("'", "''").Replace(" ", "_") + "'");


                    if (drReportAttrib.Length > 0)
                    {
                        dtTemp = parseForDataType(dc, ref dtTemp, sUTC_Offset, drReportAttrib[0]);

                        DataColumn dctemp1 = dtTemp.Columns[dc.ColumnName];
                        string datatype = dc.DataType.Name;
                        string moddatatype = GetDataTypeForQueries(datatype);
                        SetDataTypeofColumn(ref dctemp1, moddatatype);
                    }
                }
            }
            dtData = dtTemp;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("ProcessDataTable : Error : " + Ex.Message);
            return false;
        }
        return true;
    }

    // Added by srivatsan for datatype of queries
    private string GetDataTypeForQueries(string datatype)
    {
        string result = "TX";
        try
        {
            switch (datatype.Trim().ToLower())
            {
                case "string":
                    result = "TX";
                    break;
                case "int32":
                    result = "NU";
                    break;
                case "decimal":
                    result = "DC";
                    break;
                case "datetime":
                    result = "DA";
                    break;
                case "boolean":
                    result = "BO";
                    break;
                default:
                    result = "TX";
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDataTypeForQueries :" + ex.Message);
        }
        return result;

    }

    /// <summary>
    /// This to check whether the data type is Date or DateTime
    /// If type is date, then Hours(time difference) need not be added.
    /// If type is datetime, then Hours should be added.
    /// </summary>
    /// <returns></returns>
    private bool IsDateField(DataTable dtdata, DataColumn dc)
    {

        bool status = false;

        try
        {
            if (dtdata != null)
            {
                DataTable dt = dtdata.Copy();
                DataColumn dcol = new DataColumn("temp_" + dc.ColumnName);
                dcol.Expression = "Convert(" + dc.ColumnName + ",'System.String')";
                dt.Columns.Add(dcol);

                DataRow[] drr = dt.Select("" + dcol.ColumnName + " like '%12:00:00 AM%'");

                //DataRow[] drrtotalcount = dtdata.Select(dc.ColumnName + " <> ''"); // Commanded by 'Imran Gani' on 30-Jul-2012.
                DataRow[] drrtotalcount = dt.Select("" + dcol.ColumnName + " <> ''"); // Added by 'Imran Gani' on 30-Jul-2012.
                int totalrowcount = drrtotalcount.Length;

                int selectrowcount = drr.Length;

                if (totalrowcount == selectrowcount)
                {
                    status = true;
                }


            }
        }
        catch
        {

        }


        return status;
    }

    private DataTable parseForDataType(DataColumn dc, ref DataTable dtData, ref DataRow drAttrib, ref DataRow drReportAttrib, string UTC_Offset)
    {
        DataTable dtProcessed = dtData.Copy();
        try
        {
            DynamicDisplayI DDI = new DynamicDisplayI();
            //string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            string sDataType = drAttrib["attrib_data_type"].ToString();
            int iFieldLength = 0;//int iFieldLength = dc.ColumnName.Length;
            //            SetDataTypeofColumn(ref dc, sDataType); // Added by srivatsan for assigning DataType as extended property of the dataTable
            switch (sDataType.ToLower())
            {
                case "da":
                    dtProcessed.Columns.Add(new DataColumn("", Type.GetType("System.String")));
                    //Localization ll = new Localization();
                    foreach (DataRow dr in dtProcessed.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                        {
                            DateTime dt = DateTime.Parse(dr[dc.ColumnName].ToString());
                            //dr["Column1"] = dt.ToString(ll.getDateFormat());
                            dr["Column1"] = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), dt);
                            if (iFieldLength < dr["Column1"].ToString().Length)
                                iFieldLength = dr["Column1"].ToString().Length;
                        }
                    }
                    //ll = null;
                    dtProcessed.Columns.Remove(dc.ColumnName);
                    //dtProcessed.Columns["Column1"].ExtendedProperties = dc.ExtendedProperties;
                    dtProcessed.Columns["Column1"].ColumnName = dc.ColumnName;

                    break;
                case "dt":
                    dtProcessed.Columns.Add(new DataColumn("", Type.GetType("System.String")));
                    Localization li = new Localization();
                    foreach (DataRow dr in dtProcessed.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                        {
                            dr["Column1"] = li.getDateTime4TimeZone(dr[dc.ColumnName].ToString(), UTC_Offset, false, false);
                            if (iFieldLength < dr["Column1"].ToString().Length)
                                iFieldLength = dr["Column1"].ToString().Length;
                        }
                    }
                    dtProcessed.Columns.Remove(dc.ColumnName);
                    //dtProcessed.Columns["Column1"].ExtendedProperties = dc.ExtendedProperties;
                    dtProcessed.Columns["Column1"].ColumnName = dc.ColumnName;
                    break;
                //case "cu":
                //    dtProcessed.Columns.Add(new DataColumn("", Type.GetType("System.String")));
                //    loadCurrencySettings();

                //    foreach (DataRow dr in dtProcessed.Rows)
                //    {
                //        if (dr[dc.ColumnName] != System.DBNull.Value)
                //        {
                //            dr["Column1"] = DDI.manageCurrency(dr[dc.ColumnName].ToString(), currencyCode_Rate);
                //            if (iFieldLength < dr["Column1"].ToString().Length)
                //                iFieldLength = dr["Column1"].ToString().Length;
                //        }
                //    }
                //    dtProcessed.Columns.Remove(dc.ColumnName);
                //    // dtProcessed.Columns["Column1"].ExtendedProperties = dc.ExtendedProperties;
                //    dtProcessed.Columns["Column1"].ColumnName = dc.ColumnName;
                //    break;

            }
            DDI = null;

            // Added by srivatsan on June 15 2009 for owner id field
            if (drReportAttrib["attrib_id"].ToString().ToLower() == "created_by" || drReportAttrib["attrib_id"].ToString().ToLower() == "modified_by" || drReportAttrib["owner_id"].ToString().ToLower() == "owner_id")
            {
                foreach (DataRow dr in dtProcessed.Rows)
                {
                    if (dr[drReportAttrib["attrib_id"].ToString().ToLower()] != System.DBNull.Value)
                    {
                        if (dsTables.Tables["sy_usr_temp"].Select("af_row_id='" + dr[drReportAttrib["attrib_id"].ToString().ToLower()].ToString().Replace("'", "''") + "'").Length > 0)
                        {
                            dr[drReportAttrib["attrib_id"].ToString().ToLower()] = dsTables.Tables["sy_usr_temp"].Select("af_row_id='" + dr[drReportAttrib["attrib_id"].ToString().ToLower()].ToString().Replace("'", "''") + "'")[0]["display_name"].ToString();
                            if (iFieldLength < dr[drReportAttrib["attrib_id"].ToString().ToLower()].ToString().Length)
                                iFieldLength = dr[drReportAttrib["attrib_id"].ToString().ToLower()].ToString().Length;
                        }
                    }
                }
            }

            if (iFieldLength == 0)
            {
                foreach (DataRow dr in dtProcessed.Rows)
                {
                    if (dr[dc.ColumnName] != System.DBNull.Value)
                    {
                        if (iFieldLength < dr[dc.ColumnName].ToString().Length)
                            iFieldLength = dr[dc.ColumnName].ToString().Length;
                    }
                }
            }

            if (iFieldLength < drReportAttrib["caption"].ToString().Length)
                iFieldLength = drReportAttrib["caption"].ToString().Length;

            if (iFieldLength > 15 && iFieldLength <= 200)
                drReportAttrib["mb_field_length"] = iFieldLength * 0.08;// +"in";
            else if (iFieldLength > 200)
            {
                drReportAttrib["mb_field_length"] = iFieldLength * 0.005;// +"in";
            }
            else
            {
                if (iFieldLength < 6) iFieldLength = 5;
                drReportAttrib["mb_field_length"] = iFieldLength * 0.1;// +"in";
            }


        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("ParseData : Error : " + Ex.Message);
        }
        return dtProcessed;
    }

    private DataTable parseForDataType(DataColumn dc, ref DataTable dtData, string UTC_Offset, DataRow drReportAttrib)
    {
        DataTable dtProcessed = dtData.Copy();
        try
        {
            DynamicDisplayI DDI = new DynamicDisplayI();
            //string sUTC_Offset = DDI.getUserSetting("sy_usr", "time_zone", "sy_timezone", "utc_offset", "timezone_id");
            string sDataType = dtData.Columns[dc.ColumnName].DataType.ToString();
            int iFieldLength = 0;//int iFieldLength = dc.ColumnName.Length;
            SetDataTypeofColumn(ref dc, sDataType); // Added by srivatsan for assigning DataType as extended property of the dataTable
            switch (sDataType.ToLower())
            {
                /*case "da":
                    dtProcessed.Columns.Add(new DataColumn("", Type.GetType("System.String")));
                    Localization ll = new Localization();
                    foreach (DataRow dr in dtProcessed.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                        {
                            DateTime dt = DateTime.Parse(dr[dc.ColumnName].ToString());
                            dr["Column1"] = dt.ToString(ll.getDateFormat());
                            if (iFieldLength < dr["Column1"].ToString().Length)
                                iFieldLength = dr["Column1"].ToString().Length;
                        }
                    }
                    ll = null;
                    dtProcessed.Columns.Remove(dc.ColumnName);
                    dtProcessed.Columns["Column1"].ColumnName = dc.ColumnName;
                    break;*/
                case "system.datetime":
                    dtProcessed.Columns.Add(new DataColumn("", Type.GetType("System.String")));
                    Localization li = new Localization();
                    bool idate = IsDateField(dtProcessed, dc);
                    foreach (DataRow dr in dtProcessed.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                        {
                            if (!idate)
                                dr["Column1"] = li.getDateTime4TimeZone(dr[dc.ColumnName].ToString(), UTC_Offset, false, false);
                            else
                                dr["Column1"] = MBLocalization.getLocalizedDate(HttpContext.Current.Session["userlocale"].ToString(), DateTime.Parse(dr[dc.ColumnName].ToString()));
                            if (iFieldLength < dr["Column1"].ToString().Length)
                                iFieldLength = dr["Column1"].ToString().Length;
                        }
                    }
                    dtProcessed.Columns.Remove(dc.ColumnName);
                    dtProcessed.Columns["Column1"].ColumnName = dc.ColumnName;
                    break;
                /*case "cu":
                    dtProcessed.Columns.Add(new DataColumn("", Type.GetType("System.String")));
                    loadCurrencySettings();

                    foreach (DataRow dr in dtProcessed.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                        {
                            dr["Column1"] = DDI.manageCurrency(dr[dc.ColumnName].ToString(), currencyCode_Rate);
                            if (iFieldLength < dr["Column1"].ToString().Length)
                                iFieldLength = dr["Column1"].ToString().Length;
                        }
                    }
                    dtProcessed.Columns.Remove(dc.ColumnName);
                    dtProcessed.Columns["Column1"].ColumnName = dc.ColumnName;
                    break;*/
                default:
                    foreach (DataRow dr in dtProcessed.Rows)
                    {
                        if (dr[dc.ColumnName] != System.DBNull.Value)
                        {
                            if (iFieldLength < dr[dc.ColumnName].ToString().Length)
                                iFieldLength = dr[dc.ColumnName].ToString().Length;
                        }
                    }
                    break;
            }
            DDI = null;

            // Added by srivatsan on June 15 2009 for owner id field
            if (dc.ColumnName == "created_by" || dc.ColumnName == "modified_by" || dc.ColumnName == "owner_id")
            {
                foreach (DataRow dr in dtProcessed.Rows)
                {
                    if (dr[dc.ColumnName] != System.DBNull.Value)
                    {
                        if (dsTables.Tables["sy_usr_temp"].Select("af_row_id='" + dr[dc.ColumnName].ToString().Replace("'", "''") + "'").Length > 0)
                        {
                            dr[dc.ColumnName] = dsTables.Tables["sy_usr_temp"].Select("af_row_id='" + dr[dc.ColumnName].ToString().Replace("'", "''") + "'")[0]["display_name"].ToString();
                            if (iFieldLength < dr[dc.ColumnName].ToString().Length)
                                iFieldLength = dr[dc.ColumnName].ToString().Length;
                        }
                    }
                }
            }

            if (iFieldLength == 0)
            {
                foreach (DataRow dr in dtProcessed.Rows)
                {
                    if (dr[dc.ColumnName] != System.DBNull.Value)
                    {
                        if (iFieldLength < dr[dc.ColumnName].ToString().Length)
                            iFieldLength = dr[dc.ColumnName].ToString().Length;
                    }
                }
            }

            if (iFieldLength < drReportAttrib["caption"].ToString().Length)
                iFieldLength = drReportAttrib["caption"].ToString().Length;

            if (iFieldLength > 15)
                drReportAttrib["mb_field_length"] = iFieldLength * 0.08;// +"in";
            else
            {
                if (iFieldLength < 6) iFieldLength = 5;
                drReportAttrib["mb_field_length"] = iFieldLength * 0.1;// +"in";
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("ParseData : Error : " + Ex.Message);
        }
        return dtProcessed;
    }

    private void loadCurrencySettings()
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        ArrayList cols = new ArrayList();
        cols.Add("c_rate"); cols.Add("c_code");
        currencyCode_Rate = DDI.getUserSetting("sy_usr", "currency_id", "sy_currency", cols, "c_code");
        currencyCode_Rate.Add(DDI.getCorporateCurrency());
        DDI = null;
    }

    private DataSet getAttribDataType(ref DataTable dtData, ref DataSet dsPageInfo)
    {
        DataSet ds = new DataSet();
        try
        {

            HDDatabase HDD = new HDDatabase();

            string sSql = "";
            //modified by Sampath for new report designer
            if (dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString() == "" || dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "false" || dsPageInfo.Tables["p_sy_report"].Rows[0]["rpt_base_object"].ToString().ToLower() == "object")
            {
                sSql = "Select * from sy_obj";

                DataTable dtObj = HDD.GetDataTable(sSql, "sy_obj_temp");
                //dtObj.TableName = "sy_obj_temp";
                ds.Tables.Add(dtObj.Copy());
                foreach (DataRow dr in dsPageInfo.Tables["p_sy_report_att"].Rows)
                {
                    if (!ds.Tables.Contains(dr["object_id"].ToString() + "_att"))
                    {
                        sSql = "select * from sy_obj_att where object_id='" + ds.Tables["sy_obj_temp"].Select("object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'")[0]["af_row_id"].ToString() + "'";
                        DataTable dt = HDD.GetDataTable(sSql);
                        dt.TableName = dr["object_id"].ToString() + "_att";
                        ds.Tables.Add(dt.Copy());
                        dt.Dispose();
                        dt = null;
                    }
                }

                sSql = "select * from sy_obj_mas_detail";
                ds.Tables.Add(HDD.GetDataTable(sSql, "sy_obj_mas_detail_temp").Copy());

                sSql = "select * from sy_bnd";
                ds.Tables.Add(HDD.GetDataTable(sSql, "sy_bnd_temp").Copy());

                sSql = "select * from sy_pg";
                ds.Tables.Add(HDD.GetDataTable(sSql, "sy_pg_temp").Copy());

                sSql = "select * from sy_pg_ctr";
                ds.Tables.Add(HDD.GetDataTable(sSql, "sy_pg_ctr_temp").Copy());
            }

            string sDisplayName = getUserDisplayName();

            sSql = "select *, " + sDisplayName + " as display_name from sy_usr";
            ds.Tables.Add(HDD.GetDataTable(sSql, "sy_usr_temp").Copy());

            HDD = null;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("getAttribDataType : Error : " + Ex.Message);
        }
        return ds;
    }

    #region MyRegion
    //private void parseForUser(ref DataTable dtData)
    //{
    //    try
    //    {
    //        string sDisplayName = getUserDisplayName();

    //        string sSql = "select *, " + sDisplayName + " as display_name from sy_usr";
    //        HDDatabase HDD = new HDDatabase();
    //        dsTables.Tables.Add(HDD.GetDataTable(sSql,"sy_usr").Copy());
    //    }

    //    catch (Exception Ex)
    //    {
    //    }
    //} 
    #endregion

    private string getUserDisplayName()
    {
        HDDatabase HDD = new HDDatabase();
        string userDisplayField = HDD.GetColumnValue("sy_acr_mem", "mem_id", "af_row_id='30583eb791cb7d5b'");
        userDisplayField = userDisplayField.Trim().Length == 0 ? "user_id" : userDisplayField;
        HDD = null;
        return userDisplayField;
    }

    private void parseForMasterDetail(ref DataTable dtData, ref DataSet dsReportInfo, ref DataSet dsTables)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataRow[] drr = dsReportInfo.Tables["p_sy_report_att"].Select("object_id<>'" + dsReportInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString().Replace("'", "''") + "'");

            if (drr.Length > 0)
            {
                foreach (DataRow dr in drr)
                {
                    //DataRow[] drObjects = dsTables.Tables["sy_obj_temp"].Select("object_id='" + dsReportInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString() + "'");
                    DataRow[] drObjects = dsTables.Tables["sy_obj_temp"].Select("object_id='" + drr[0]["object_id"].ToString().Replace("'", "''") + "'");

                    if (drObjects.Length > 0)
                    {
                        string sObject_Id = drr[0]["object_id"].ToString();
                        string sSelectedObjectRowId = dsTables.Tables["sy_obj_temp"].Select("object_id='" + dsReportInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString().Replace("'", "''") + "'")[0]["af_row_id"].ToString();
                        //string sObject_Id = drObjects[0]["af_row_id"].ToString();
                        string sAttrib_Id = "";
                        string sDisplay_att = "";
                        if (getMasterDetailInfo(ref dsTables, ref sObject_Id, ref sAttrib_Id, ref sDisplay_att, sSelectedObjectRowId))
                        {
                            //DataRow[] drTable = dsTables.Tables["sy_obj_temp"].Select("object_id='" + drObjects[0][""].ToString() + "'");
                            //if (drTable.Length > 0)
                            //{
                            //string sSql = "select * from " + drTable[0]["object_table"].ToString();
                            string sSql = "select * from [" + drObjects[0]["object_table"].ToString() + "]";
                            dsTables.Tables.Add(HDD.GetDataTable(sSql, drObjects[0]["object_table"].ToString()).Copy());
                            substituteData(ref dtData, dsTables.Tables[drObjects[0]["object_table"].ToString()], "af_row_id", sAttrib_Id, sDisplay_att);
                            //}
                        }
                    }
                }
            }
            HDD = null;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("parseForMasterDetail : Error : " + Ex.Message);
        }
    }

    private bool getMasterDetailInfo(ref DataSet dsTables, ref string Object_id, ref string Attrib_id, ref string Display_Attrib, string SelectedObjectRowId)
    {
        try
        {
            DataRow[] drr = dsTables.Tables["sy_obj_mas_detail_temp"].Select("master_obj='" + Object_id.Replace("'", "''") + "' and object_id='" + SelectedObjectRowId.Replace("'", "''") + "'");
            if (drr.Length > 0)
            {
                Object_id = drr[0]["object_id"].ToString();
                Attrib_id = drr[0]["attrib_id"].ToString();
                Display_Attrib = drr[0]["display_att"].ToString();
            }
            else
                return false;
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("getMasterDetailInfo : Error : " + Ex.Message);
            return false;
        }
        return true;
    }

    private void substituteData(ref DataTable dtData, DataTable dtSource, string DataColumnName, string SourceDataColumn, string SourceLookupColumn)
    {
        try
        {
            foreach (DataRow dr in dtData.Rows)
            {
                if (dr[SourceDataColumn].ToString() != "")
                {
                    DataRow[] drLookup = dtSource.Select(DataColumnName + "='" + dr[SourceDataColumn].ToString().Replace("'", "''") + "'");
                    if (drLookup.Length > 0)
                        dr[SourceDataColumn] = drLookup[0][SourceLookupColumn];
                }
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("substituteData : Error : " + Ex.Message);
        }
    }

    private void parseForBindFields(ref DataTable dtData, ref DataSet dsReportInfo, ref DataSet dsTables)
    {
        try
        {
            string sPage_id = "";
            string sBind_id = "";
            DataTable dtTemp = dtData.Copy();
            DataRow[] drr = dsTables.Tables["sy_pg_temp"].Select("object_id='" + dsReportInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString().Replace("'", "''") + "'");
            if (drr.Length > 0)
            {
                sPage_id = drr[0]["af_row_id"].ToString();

                foreach (DataColumn dc in dtData.Columns)
                {
                    DataRow[] drPageControl = dsTables.Tables["sy_pg_ctr_temp"].Select("page_id='" + sPage_id.Replace("'", "''") + "' and control_attrib_id='" + dc.ColumnName.Replace("'", "''") + "'");

                    if (drPageControl.Length > 0)
                    {
                        if (drPageControl[0]["control_bind_id"].ToString() != "")
                        {
                            string sBind_Text = "";
                            string sBind_Value = "";

                            DataTable dtBind = getBindTable(drPageControl[0]["control_bind_id"].ToString(), ref sBind_Text, ref sBind_Value);
                            //DataTable dtBind = HDD.GetDataTable(objBC.GetBindSql_forValue(drPageControl[0]["control_bind_id"].ToString()));

                            //dtTemp = changeColumnDataType(ref dtTemp, dc.ColumnName); // Commented by 'Imran Gani' on 19-Mar-2014, for MBLocale
                            substituteData(ref dtTemp, dtBind, "bind_value", dc.ColumnName, "bind_text");
                            Localization loc = new Localization(); // Added by 'Imran Gani' on 19-Mar-2014, for MBLocale
                            dtTemp = loc.getLocalizedColumns(dtTemp, drPageControl[0]["control_attrib_type"].ToString(), dc.ColumnName);
                            loc = null;
                        }
                    }
                }
            }
            dtData = dtTemp.Copy();
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("parseForBindFields : Error : " + Ex.Message);
        }
    }

    private DataTable getBindTable(string strBindRowID, ref string Bind_Text, ref string Bind_Value)
    {
        DataTable dt = new DataTable();
        try
        {
            DataRow[] drr = dsTables.Tables["sy_bnd_temp"].Select("af_row_id = '" + strBindRowID.Replace("'", "''") + "'");

            if (drr.Length > 0)
            {
                Bind_Text = drr[0]["bind_text"].ToString();
                Bind_Value = drr[0]["bind_value"].ToString();
                string sBind_Condition = drr[0]["bind_parameter"].ToString();

                if (sBind_Condition.Trim() == "")
                {
                    sBind_Condition = " 1 = 1 ";
                }

                //string sSql = "select " + Bind_Text + " as bind_text, " + Bind_Value + " as bind_value from " + drr[0]["bind_table"].ToString() + " where " + sBind_Condition;
                string sSql = "select " + Bind_Text + " as bind_text, " + Bind_Value + " as bind_value from " + drr[0]["bind_table"].ToString();

                HDDatabase HDD = new HDDatabase();
                dt = HDD.GetDataTable(sSql + " where " + sBind_Condition); // Added by 'Imran Gani' on 19-Mar-2014, for bind where key handling
                if (dt == null || dt.Columns.Count == 0)
                    dt = HDD.GetDataTable(sSql + " " + sBind_Condition);
                HDD = null;
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("getBindTable : Error : " + Ex.Message);
        }
        return dt;
    }

    private DataTable changeColumnDataType(ref DataTable dtData, string ColumnName)
    {
        DataTable dtNew = dtData.Copy();
        try
        {
            DataTable dtTemp = dtData.Copy();
            if (dtData.Columns[ColumnName].DataType != Type.GetType("System.String"))
            {
                dtNew.Columns.Remove(ColumnName);
                DataColumn dc = new DataColumn(ColumnName);
                dtNew.Columns.Add(dc);
                for (int iRow = 0; iRow < dtData.Rows.Count; iRow++)
                    dtNew.Rows[iRow][ColumnName] = dtTemp.Rows[iRow][ColumnName].ToString();
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("changeColumnDataType : Error : " + Ex.Message);
        }
        return dtNew;
    }

    public string getObjectName(string ObjectId)
    {
        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["dbcon"].ToString());
        string sObjectName = hdd.GetColumnValue("Select object_table from sy_obj where object_id = '" + ObjectId + "'");
        hdd = null;
        return sObjectName;
    }

    public string getSql(ref DataSet dsInputInfo)
    {
        string sSql = "";
        string sTableName = getObjectName(dsInputInfo.Tables["p_sy_report_obj"].Rows[0]["object_id"].ToString());
        string sFieldName = getFieldNames(dsInputInfo.Tables["p_sy_report_att"], sTableName);

        if (sFieldName != "")
        {
            sSql = "Select " + sFieldName + " from " + sTableName;
        }

        sSql = sSql + " where 1=1";

        return sSql;
    }

    private string getFieldNames(DataTable dtAttribute, string sObjectName)
    {
        string sFields = "";

        foreach (DataRow dr in dtAttribute.Rows)
        {
            string sAttrib_id = dr["attrib_id"].ToString();
            sFields = sFields + " [" + sObjectName + "].[" + sAttrib_id + "],"; //+ "] as [" + dr["caption"].ToString() + "], " ;
        }

        sFields = sFields.Trim();

        if (sFields.EndsWith(","))
            sFields = sFields.Trim(',');

        return sFields;
    }

}

